public class KmpTest {
public static void main(String[] args) {
System.out.println(new KmpSulution().strStr("abababababc", "ababc"));
System.out.println(new KmpSulution().strStr("abcabcabcd", "abcde"));
}
public int strStr(String haystack, String needle) {
int i = 0;
int j = 0;
int[] next = getNext(needle);
while (i < haystack.length() && j < needle.length()) {
if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == needle.length()) {
return i - j;
} else {
return -1;
}
}
public int[] getNext(String sub) {
int[] next = new int[sub.length() + 1];
int i = 0;
int j = -1;
while (i < sub.length()) {
if (j == -1 || sub.charAt(i) == sub.charAt(j)) {
next[++i] = ++j;
} else {
j = next[j];
}
}
return next;
}
}
kmp算法 Java
最新推荐文章于 2024-04-26 14:00:07 发布