Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle"is a rotation of"erbottlewat").
The rotation would not change the length of the string, so first check the length of the two strings.
Then, if s2 is a rotation of s1, we could divide s1 into to parts, str1str2, where the breakpoint is where rotation appear.
Then s2 should be str2str1. If we append s2 to itself, we would get a str2str1str2str1 = str2s1str1,
where s1 should be a substring of it. This is just what we want. The append process is O(N),
so the true time complexity depends on the isSubstring() function. The space complexity is O(N).
/*The rotation would not change the length of the string, so first check the length of the two strings. Then, if s2 is a rotation of s1, we could divide s1 into to parts, str1str2, where the breakpoint is where rotation appear. Then s2 should be str2str1. If we append s2 to itself, we would get a str2str1str2str1 = str2s1str1, where s1 should be a substring of it. This is just what we want. The append process is O(N), so the true time complexity depends on the isSubstring() function */ public class IsRotation { // is s2 a substring of s1 using KMP algorithm public boolean isSubstring(String s1, String s2) { int n = s2.length(); if(n == 0) return true; int[] next = new int[n]; next[0] = 0; int i = 1, j = 0; for(i = 1; i < n; i++) { if(s2.charAt(i) == s2.charAt(j)) { j++; next[i] = j; } else { while(j > 0 && s2.charAt(j) != s2.charAt(i)) j = next[j-1]; if(s2.charAt(j) == s2.charAt(i)) j++; next[i] = j; } } i = 0; j = 0; while(i < s1.length() && j < s2.length()) { if(s1.charAt(i) == s2.charAt(j)) { i++; j++; } else { if(j == 0) i++; else j = next[j-1]; } } if(j == s2.length()) return true; return false; } public boolean isRotation(String s1, String s2) { if(s1.length() != s2.length()) return false; String ss2 = s2 + s2; return isSubstring(ss2, s1); } public static void main(String[] args) { IsRotation ir = new IsRotation(); System.out.println(ir.isRotation("", "")); System.out.println(ir.isRotation("a", "")); System.out.println(ir.isRotation("abc", "bca")); System.out.println(ir.isRotation("abcd", "dcab")); System.out.println(ir.isRotation("waterbottle", "erbottlewat")); } }