Monday, July 17, 2017

Is string rotation of other string


/**
 * Problem: 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”).
 */
public class IsSubString {

    /*
    Solution: Concat s1 with itself and now check if it contains s2.
     */
    public  boolean isRotation(String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        String newString = s2+s2;
        return newString.indexOf(s1) != -1;
    }

}

No comments:

Post a Comment