信息竞赛中,KMP大概是字符串方面最经典的算法了。参考了部分代码,KMP的写法大概有两种
- 在原有字符串上进行KMP
#include <bits/stdc++.h>
using namespace std;
const int S = 1000010;
int kmp[S], len_a, len_b, j;
char a[S], b[S];
int main() {
scanf("%s", a + 1);
scanf("%s", b + 1);
len_a = strlen(a + 1);
len_b = strlen(b + 1);
for (int i = 2; i <= len_b; i++) {
while (j && b[i] != b[j + 1]) j = kmp[j];
if (b[j + 1] == b[i]) j++;
kmp[i] = j;
}
j = 0;
for (int i = 1; i <= len_a; i++) {
while (j > 0 && b[j + 1] != a[i]) j = kmp[j];
if (b[j + 1] == a[i]) j++;
if (j == len_b) {
printf("%d\n", i - len_b + 1);
j = kmp[j];
}
}
for (int i = 1; i <= len_b; i++)
printf("%d ", kmp[i]);
printf("\n");
return 0;
}
- 在嫁接字符串上进行KMP
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = 1000010;
int pi[M + N], n, m;
void prefix(string s) {
int len = s.length();
for (int i = 1; i < len; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) j = pi[j - 1];
if (s[i] == s[j]) j++;
pi[i] = j;
}
}
int main() {
string s, t;
cin >> s >> t;
n = s.length(), m = t.length();
prefix(s + " " + t);
for (int i = n + 1; i <= n + m; i++)
if (pi[i] == n) printf("%d ", i - 2 * n);
printf("\n");
return 0;
}
至于KMP算法的解释,个人认为OI-Wiki上提供的解释很详尽
KMP算法的一般应用一般是字符串匹配