Interview question: Check if one string is a rotation of other string [closed] Interview question: Check if one string is a rotation of other string [closed] java java

Interview question: Check if one string is a rotation of other string [closed]


First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1:

algorithm checkRotation(string s1, string s2)   if( len(s1) != len(s2))    return false  if( substring(s2,concat(s1,s1))    return true  return falseend

In Java:

boolean isRotation(String s1,String s2) {    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);}


Surely a better answer would be, "Well, I'd ask the stackoverflow community and would probably have at least 4 really good answers within 5 minutes". Brains are good and all, but I'd place a higher value on someone who knows how to work with others to get a solution.


Another python example (based on THE answer):

def isrotation(s1,s2):     return len(s1)==len(s2) and s1 in 2*s2