原文:
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”).
译文:
假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。
不多说了,和那道找链表是否有环一类的题目,属于你看过就会而且忘不掉,没看过就跪的神题。
package Arrays_Strings;
public class S1_8 {
public static boolean isSubstring(String big, String small) {
if(big.indexOf(small) >= 0) {
return true;
}
return false;
}
// 检查办法就是把两个s1拼起来
public static boolean isRotation(String s1, String s2) {
int len = s1.length();
if(len == s2.length() && len>0) {
String s1s1 = s1 + s1;
return isSubstring(s1s1, s2);
}
return false;
}
public static void main(String[] args) {
String[][] pairs = {{"apple", "pleap"}, {"waterbottle", "erbottlewat"}, {"camera", "macera"}};
for (String[] pair : pairs) {
String word1 = pair[0];
String word2 = pair[1];
boolean is_rotation = isRotation(word1, word2);
System.out.println(word1 + ", " + word2 + ": " + is_rotation);
}
}
}