Skip to content

Instantly share code, notes, and snippets.

@chouclee
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chouclee/a9946f058856cdbb73f5 to your computer and use it in GitHub Desktop.
Save chouclee/a9946f058856cdbb73f5 to your computer and use it in GitHub Desktop.
[CC150][1.8] 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 (i e , “waterbottle” is a rotation of “erbottlewat”)
public class isRotation {
public static boolean isRotate(String s1, String s2) {
if (s1.length() != s2.length()) return false;
return isSubstring(s2, s1.concat(s1));
}
public static boolean isSubstring(String s1, String s2) {
int l2 = s2.length();
int l1 = s1.length();
if (l1 > l2) return false;
if (l1 == 0 && l2 == 0) return true;
int k, j;
for (int i = 0; i < l2; i++ ) {
k = i;
j = 0;
while (s2.charAt(k++) == s1.charAt(j++)) {
if (j == l1) return true;
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "erbottlewat";
String b = "water";
if (isRotation.isRotate(a, b))
System.out.println("Yes");
else
System.out.println("No");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment