Saturday, 31 January 2015

Check if a string is a rotation of other given String




In a rotation we cut a string at a rotation point such that on rotation eg -
jimmy <=> myjim
So ,
s1 = "jimmy" = x + y where y = "my" and x = "jim" 
s2 = "myjim" = y + x
So if a rotated string  "myjim" has to be a rotation of "jimmy" then it should be a substring of  - xyxy = "jimmyjimmy" = s1s1

So checking if a string "myjim" is a substring of a String xyxy = "jimmyjimmy" will prove that it is an rotation of String xy = "jimmy"
 



public  isRot(String s1 , String s2)
{
    int len =  s1.length();
    // if both  strings are of same length and not empty
    if(len == s2.length() && len >= 0  )
    {
        // concatanate string s1 within new buffer
        String s1s1 = s1+s1;
        return isSubString(s1s1 , s2);
    }
    return false;
   
}


public static boolean isSubString(String big , String small)
{
    if(big.indexOf(small) >= 0)
        return ture ;
    else
        return false;
}

No comments:

Post a Comment