Thursday, February 29, 2024
HomeSoftware EngineeringThe best way to Calculate String Rotation in Java

# The best way to 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 should always shift the primary string ahead to match the second. The test needs to be case-sensitive.

For 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#

Possibility 1:

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

Possibility 2:

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

Possibility 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;
}

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

## Check instances to validate our answer#

``````import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class RotationTest {
@Check
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