#include <cstdio>
#include <cstring>
#define N 1000010
using namespace std;
char s[N],t[N];
int next[N];
int main() {
scanf("%s%s", s, t);
int m = strlen(s), n = strlen(t);
next[0] = -1;
for (int i = 1; i < n; i++) {
int k = next[i - 1];
while (k > -1 && t[k + 1] != t[i])
k = next[k];
if (t[k + 1] == t[i]) k++;
next[i] = k;
}
int k = 0;
for (int i = 0; i < m; i++) {
while (k > -1 && s[i] != t[k + 1])
k = next[k];
if (s[i] == t[k + 1]) k++;
if (k == n - 1) {
k = next[k];
printf("%d\n", i - n + 2);
}
}
for (int i = 0; i < n; i++)
printf("%d ", next[i] + 1);
return 0;
}
【模板】KMP
最新推荐文章于 2025-05-09 15:51:02 发布
本文深入解析了一种高效的字符串匹配算法,通过预处理模式串生成next数组,加速在目标串中查找模式串的过程。代码示例详细展示了算法实现,包括模式串的next数组构造和目标串的匹配过程。
1005

被折叠的 条评论
为什么被折叠?



