Last active
August 29, 2015 14:02
-
-
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”)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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