kmp算法 获取next与nextval数组
作者:
Quann
,
2024-03-22 20:56:13
,
所有人可见
,
阅读 12
#include <bits/stdc++.h>
#define debug(x) cout << #x << ' ' << x << '\n'
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
const int N = 100010, M = 1000010, mod = 1e9 + 7, inf = 0x3f3f3f3f;
int n, m;
int ne[N];
char p[N], s[M]; // p为较短的字符串
int nextval[N];
void get_nexts(int next[])
{
int i = 1, j = 0;
ne[1] = 0;
while (i <= n)
{
if (j == 0 || p[i] == p[j])
ne[++i] = ++j;
else
j = ne[j];
}
}
void get_nextvals(int next[], int nextval[])
{
nextval[1] = 0;
int j = 2;
while (j <= n)
{
if (p[next[j]] == p[j])
nextval[j] = nextval[next[j]];
else
nextval[j] = next[j];
j++;
}
}
void kmp(int next[])
{
int i = 1, j = 1;
while (i <= m)
{
if (j == 0 || s[i] == p[j]) // j==0表示第一个不匹配
i++, j++;
else
j = ne[j];
if (j == n + 1)
{
cout << i - j << ' '; // i已经移动了所以应该减去n+1
j = ne[j];
}
}
}
void solve()
{
cin >> n >> p + 1 >> m >> s + 1;
int next[N];
get_nexts(next);
get_nextvals(nextval, next);
// 1. next数组求解
kmp(next);
// 2. next优化数组求解
kmp(nextval);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
solve();
return 0;
}