String Rotation

经典题目

String Rotation

Check whether string t is shifted, given string s

// We need to check if there is 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 s1s1.

public boolean solution(String s1, String s2) {
    // Assume s1 and s2 are not null.
    if(s1.length() != s2.length()) {
        return false;
    } else {
        String s1s1 = s1 + s1;
        return isSubstring(s1s1, s2);
    }

    return false;
}

// Time Complexity: O(N), assuming that isSubstring runs in O(A + B) time
// Space Complexity: O(N)

Last updated