KMP 算法
void getNext(char* p)
{
int len = (int)strlen(p + 1);
for (int i = 2, j = 0; i <= len; i++) {
while (j && p[i] != p[j + 1]) j = nxt[j];
if (p[i] == p[j + 1]) j++;
nxt[i] = j;
}
}
void kmp(char* s, char* p)
{
int slen = (int)strlen(s + 1), plen = (int)strlen(p + 1);
for (int i = 1, j = 0; i <= slen; i++) {
while (j && s[i] != p[j + 1]) j = nxt[j];
if (s[i] == p[j + 1]) j++;
if (j == plen) {
printf("%d\n", i - plen + 1);
j = nxt[j];
}
}
}
最后更新于
这有帮助吗?