public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
int[] next = new int[m];
for (int i = 1, j; i < m; i++) {
j = next[i - 1];
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
next[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
KMP算法模板
于 2021-06-30 20:25:22 首次发布