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 (e.g., "waterbottle" is a rotation of "erbottlewat").
Hint
- If a string is a rotation of another, then it's a rotation at a particular point. For example, a rotation of waterbottle at character 3 means cutting waterbottle at character 3 and putting the right half (erbottle) before the left half (wat).
- We are essentially asking if there's a way of splitting the first string into two parts, x and y, such that the first string is xy and the second string is yx. For example, x = wat and y = erbottle. The first string is xy = waterbottle. The second string is yx = erbottlewat.
- Think about the earlier hint. Then think about what happens when you concatenate erbottlewat to itself. You get erbottlewaterbottlewat.
Solution
本题给定两个字符串,让我们判断其中一个字符串是否为另一个的旋转字符串,此外还给了一个isSubstring函数来调用,不过规定只能调用一次。这里可以发现一个规律,若将一个字符串重复拼接,假如另一个字符串是拼接后字符串的子串,则它们就互为旋转字符串。
令 x = wat, y = erbottle
若有 s1 = xy, s2 = yx,显然它们互为旋转字符串
重复拼接 s1s1 = xyxy, 则可以看到 s2 为 s1s1 的子串
public boolean isStringRotation(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() != s2.length()) return false;
return isSubstring(s1 + s1, s2);
}