A: a b a b a b c
B: a b a b c
Next: 0 0 1 2 0
暴力:
1
A: a b a b a b c
B: a b a b c
2
A: a b a b a b c
B: a b a b c
3
A: a b a b a b c
B: a b a b c
KMP
1
0 1 2 3 4 5 6
A: a b a b a b c
B: a b a b c
Next: 0 0 1 2 0
2.
A[4]
B[2]
A: a b a b a b c
B: a b a b c
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
char str1[maxn], str2[maxn];
int Next[maxn];
void get_Next()
{
int i, j, m = strlen(str2);
Next[0] = 0;
for(i = 1; i < m; i++)
{
j = Next[i - 1];
while(j > 0 && str2[i] != str2[j])
{
j = Next[j - 1];
}
if(str2[i] == str2[j])
Next[i] = j + 1;
else
Next[i] = 0;
}
}
int kmp()
{
int len1 = strlen(str1), len2 = strlen(str2);
int i, j, ans = 0;
for(i = 0, j = 0; i < len1; i++)
{
while(j > 0 && str1[i] != str2[j])
{
j = Next[j - 1];
}
if(str1[i] == str2[j])
j++;
if(j == len2)
{
ans++;
j = Next[j - 1];//可重复的 比如 AZA
// AZAZAZA 输出3
// j = 0; 输出2 不可重复
}
}
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%s %s", str2, str1);
get_Next();
for(int i=0;i<20;i++){
printf("%d ",Next[i]);
}
int v = kmp();
printf("%d\n", v);
}
}