Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Last active August 29, 2015 14:03
Show Gist options
  • Save WOLOHAHA/944d41076b3b76d64156 to your computer and use it in GitHub Desktop.
Save WOLOHAHA/944d41076b3b76d64156 to your computer and use it in GitHub Desktop.
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").
public class Main {
/**
* 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 (e.g.,"waterbottle"is
* a rotation of"erbottlewat").
*
* Solution: just the same as CTCI
* If we imagine that s2 is a rotation of s1,then we can
* ask what the rotation point is.For example,if you rotate
* waterbottle after wat,you get erbottlewat.In a rotation,we
* cut s1 in to two parts,x and y,and rearrange them to get s2.
*
* s1=xy=waterbottel
* x=wat
* y=erbottel
* s2=yx=erbottelwat
*
* So,we need to check if there's a way to split s1 into x and
* y such that xy=s1 and yx=s2.Regardless of where the division
* between x and y is,we can see that yx will always be a
* substring of xyxy.That is,s2 will always be a substring of slsl.
*
* @Runtime & spaces
* runtime: O(n)
* space: O(1)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Main so = new Main();
String s1="waterbottle";
String s2="erbottlewat";
System.out.println(so.isRotation(s1, s2));
}
public boolean isRotation(String s1,String s2){
if(s1==null||s2==null||s1.length()!=s2.length())
return false;
if(s1.equals("")&&s2.equals(""))
return true;
String s1s1=s1+s1;
return isSubstring(s1s1,s2);
}
private boolean isSubstring(String s1s1, String s2) {
// TODO Auto-generated method stub
int len=s2.length();
for(int i=0;i<len;i++){
System.out.println(s1s1.subSequence(i, i+len));
if(s1s1.subSequence(i, i+len).equals(s2))
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment