Saturday, February 25, 2023
HomeSoftware EngineeringHow you can Calculate String Rotation in Java

How you can Calculate String Rotation in Java


The problem

Write a perform that receives two strings and returns n, the place n is the same as the variety of characters we must always shift the primary string ahead to match the second. The verify ought to be case-sensitive.

As an example, take the strings “fatigue” and “tiguefa”. On this case, the primary string has been rotated 5 characters ahead to provide the second string, so 5 could be returned. If the second string isn’t a legitimate rotation of the primary string, the strategy returns -1.

Examples:

"espresso", "eecoff" => 2
"eecoff", "espresso" => 4
"moose", "Moose" => -1
"is not", "'tisn" => 2
"Esham", "Esham" => 0
"canine", "god" => -1

The answer in Java code

Choice 1:

public class CalculateRotation {
  static int shiftedDiff(String first, String second){
    if (first.size() != second.size()) return -1;
    return (second + second).indexOf(first);
  }
}

Choice 2:

public class CalculateRotation {
  static int shiftedDiff(String first, String second) {
    return (first.size() <= second.size()) ?
           (second + second).indexOf(first) : -1;
  }
}

Choice 3:

public class CalculateRotation {
   static int shiftedDiff(String first, String second){
        for (int i = 0; i <= first.size(); i++) {
            if (second.equals(first)) return i;
            first = shift(first);
        }
        return -1;
    }

    non-public static String shift(String phrase) {
        return phrase.substring(phrase.size() - 1) + phrase.substring(0, phrase.size() - 1);
    }
}

Take a look at circumstances to validate our resolution

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class RotationTest {
    @Take a look at
    public void take a look at() {
      assertEquals(-1, CalculateRotation.shiftedDiff("hoop","pooh"));
      assertEquals(2, CalculateRotation.shiftedDiff("espresso","eecoff"));
      assertEquals(4, CalculateRotation.shiftedDiff("eecoff","espresso"));
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments