Tags

Feb 22, 2012

Check if one string is a rotation of other string

Two string s1 and s2 how will you check if s1 is a rotated version of s2

For Example:
if s1=avs then the following are some of its rotated versions:
vsa
sav
vas
where as "vas" is not a rotated version.
algorithm checkRotation(string s1, string s2) 
  if( len(s1) != len(s2))
    return false
  if( substring(s2,concat(s1,s1))
    return true
  return false
end
In Java:
boolean isRotation(String s1,String s2) {
    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

No comments:

Post a Comment