How to Calculate String Rotation in Java

The challenge

Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. The check should be case-sensitive.

For instance, take the strings “fatigue” and “tiguefa”. In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn’t a valid rotation of the first string, the method returns -1.

Examples:

"coffee", "eecoff" => 2 "eecoff", "coffee" => 4 "moose", "Moose" => -1 "isn't", "'tisn" => 2 "Esham", "Esham" => 0 "dog", "god" => -1
Code language: PHP (php)

The solution in Java code

Option 1:

public class CalculateRotation { static int shiftedDiff(String first, String second){ if (first.length() != second.length()) return -1; return (second + second).indexOf(first); } }
Code language: Java (java)

Option 2:

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

Option 3:

public class CalculateRotation { static int shiftedDiff(String first, String second){ for (int i = 0; i <= first.length(); i++) { if (second.equals(first)) return i; first = shift(first); } return -1; } private static String shift(String word) { return word.substring(word.length() - 1) + word.substring(0, word.length() - 1); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class RotationTest { @Test public void test() { assertEquals(-1, CalculateRotation.shiftedDiff("hoop","pooh")); assertEquals(2, CalculateRotation.shiftedDiff("coffee","eecoff")); assertEquals(4, CalculateRotation.shiftedDiff("eecoff","coffee")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments