#include <iostream>
#include <cstring>
const int N = 1000010;
using namespace std;
int n, m;
string a, b;
int nxt[N];
void pre()
{
nxt[1] = 0;
int j = 0;
for (int i = 1; i < m; i ++ )
{
while (j > 0 && b[j + 1] != b[i + 1]) j = nxt[j];
if (b[j + 1] == b[i + 1]) j ++;
nxt[i + 1] = j;
}
}
void KMP()
{
int j = 0;
for (int i = 0; i < n; i ++ )
{
while (j > 0 && b[j + 1] != a[i + 1]) j = nxt[j];
if (b[j + 1] == a[i + 1]) j ++;
if (j == m) cout << i + 1 - m + 1 << endl, j = nxt[j];
}
}
int main()
{
cin >> a >> b;
n = a.size(), m = b.size();
a = " " + a, b = " " + b;//cin >> a + 1 >> b + 1;
pre();
KMP();
for (int i = 1; i <= m; i ++ ) cout << nxt[i] << " ";
cout << endl;
}
[模板] KMP
最新推荐文章于 2024-08-31 06:24:00 发布