题目:
image.png思路:
创建一个新的字符串=str1+str1,然后用kmp看新生成的字符串里是否包含str2,包含就说明str2是str1循环右移得到的,比如字符串"abcdef",生成的新字符串是"abcdefabcdef",新字符串包含了str2所有可能的六个字符的构成方式,所以如果新生成的字符串包含str2就说明是
代码:
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));
}
网友评论