Step1 Problem:
给你字符串s2, s1。 求s2在s1中出现的次数(可重叠)。
Step2 Ideas:
个人习惯从0开始,next[0] = 0;
求出s2的next[],s2匹配完后,核心:下标移动到next[len-1],也就是前缀=后缀的最长长度,前缀的后一位的下标
Step3 Code:
#include<bits/stdc++.h>
using namespace std;
const int N = 1000005;
const int M = 10055;
char s1[N], s2[M];
int nex[M], len1, len2;
void get_nex()
{
nex[0] = 0;
for(int i = 1; i < len2; i++)
{
int j = nex[i-1];
while(j && s2[i] != s2[j])
j = nex[j-1];
if(s2[i] == s2[j]) nex[i] = j+1;
else nex[i] = 0;
}
}
void KMP()
{
int i = 0, j = 0, ans = 0;
while(i < len1 && j < len2)
{
if(s1[i] == s2[j])
i++, j++;
else {
if(!j) i++;
else j = nex[j-1];
}
if(j == len2)
{
ans++;
j = nex[j-1];//核心点
}
}
printf("%d\n", ans);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%s %s", s2, s1);
len2 = strlen(s2);
len1 = strlen(s1);
get_nex();
KMP();
}
return 0;
}