【模板】KMP字符串匹配
LJY_ljy
·
·
算法·理论
KMP算法:
1.关于scanf的字符串输入的几个毒瘤注意事项:
- 使用scanf(str1 + 1)的时候,调用长度的时候,用strlen(str1)就会返回0,只有调用strlen(str1 + 1)才能够正常返回
- 字符数组的strlen函数会龟速慢,尽量将字符数组的长度预处理出来,不要多次调用,否则直接卡成TLE
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 1000010
using namespace std;
char str1[MAXN], str2[MAXN];
int Next[MAXN], f[MAXN];
int n, m;
inline void init_next() {
m = strlen(str1 + 1);
Next[1] = 0;
for (int i = 2, j = 0; i <= m; i++) {
while (j > 0 && str1[i] != str1[j + 1]) j = Next[j];
if (str1[i] == str1[j + 1]) j++;
Next[i] = j;
}
}
inline void init_f() {
n = strlen(str2 + 1);
for (int i = 1, j = 0; i <= n; i++) {
while (j > 0 && str2[i] != str1[j + 1]) j = Next[j];
if (str2[i] == str1[j + 1]) j++;
f[i] = j;
if (f[i] == m) printf("%d\n", i - strlen(str1 + 1) + 1);
}
}
int main() {
scanf("%s %s", str2 + 1, str1 + 1);
init_next();
init_f();
for (int i = 1; i <= m; i++)
printf("%d ", Next[i]);
return 0;
}