KMP
前缀函数
约定字符串下标从
求字符串
考虑如何利用已经求出的
现在我们试图让
退而求其次,我们让待匹配下标往前跳,变为
一般地,设
-
- 否则(失配):
- 若
j = 0 ,则\pi[i] \gets 0 ,结束。 - 否则,
j \gets \pi[j-1] ,继续循环。
- 若
代码如下:
border[0] = 0;
for (int i = 1; i < (int)s.size(); i ++) {
int j = border[i - 1];
while (1) {
if (s[j] == s[i]) {
border[i] = j + 1; break;
} else {
if (!j) break;
else j = border[j - 1];
}
}
if (border[i] == (int)s2.size()) {
cout << i - 2 * (int)s2.size() + 1 << endl;
}
}
P3375 【模板】KMP
给定文本串
构造字符串
求出
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
int border[N << 1];
signed main() {
//freopen("", "r", stdin);
//freopen("", "w", stdout);
ios::sync_with_stdio(0), cin.tie(0);
string s1, s2; cin >> s1 >> s2;
string s = s2 + '#' + s1;
border[0] = 0;
for (int i = 1; i < (int)s.size(); i ++) {
int j = border[i - 1];
while (1) {
if (s[j] == s[i]) {
border[i] = j + 1; break;
} else {
if (!j) break;
else j = border[j - 1];
}
}
if (border[i] == (int)s2.size()) {
cout << i - 2 * (int)s2.size() + 1 << endl;
}
}
for (int i = 0; i < (int)s2.size(); i ++) cout << border[i] << ' ';
cout << endl;
return 0;
}