在《程序员代码面试指南》中,提到了判定两个字符串是否互为旋转词的问题
问题的描述为:如果一个字符串str,把字符串str前面任意的部分挪到后面形成的字符串叫做str的旋转词,比如 str= “12345”。str的旋转词有“12345”,“23451”,“34512”,“45123”,“51234”。
在书中提高的解法如下:
package chapter_5_stringproblem;
public class Problem_04_IsRotation {
public static boolean isRotation(String a, String b) {
if (a == null || b == null || a.length() != b.length()) {
return false;
}
String b2 = b + b;
return getIndexOf(b2, a) != -1;
}
// KMP Algorithm
public static int getIndexOf(String s, String m) {
if (s.length() < m.length()) {
return -1;
}
char[] ss = s.toCharArray();
char[] ms = m.toCharArray();
int si = 0;
int mi = 0;
int[] next = getNextArray(ms);
while (si < ss.length && mi < ms.length) {
if (ss[si] == ms[mi]) {
si++;
mi++;
} else if (next[mi] == -1) {
si++;
} else {
mi = next[mi];
}
}
return mi == ms.length ? si - mi : -1;
}
public static int[] getNextArray(char[] ms) {
if (ms.length == 1) {
return new int[] { -1 };
}
int[] next = new int[ms.length];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while (pos < next.length) {
if (ms[pos - 1] == ms[cn]) {
next[pos++] = ++cn;
} else if (cn > 0) {
cn = next[cn];
} else {
next[pos++] = 0;
}
}
return next;
}
public static void main(String[] args) {
String str1 = "yunzuocheng";
String str2 = "zuochengyun";
System.out.println(isRotation(str1, str2));
}
}
可是在java api中,有此方法:
contains
public boolean contains(CharSequence s)
- 当且仅当此字符串包含指定的 char 值序列时,返回 true。
- 是否可以更改为这样的解法:
-
在给出的测试案例中,是可以测试通过的。package JobInterview_01; public class isRotationDemo { public static boolean isRotation(String a, String b) { if (a.length() != b.length()) { return false; } String string = b + b; //public boolean contains(CharSequence s) //当且仅当此字符串包含指定的 char 值序列时,返回 true。 return string.contains(a); } public static void main(String[] args) { String str1 = "yunzuocheng"; String str2 = "zuochengyun"; System.out.println(isRotation(str1, str2)); } }