题意:
统计模式串在原串中出现了几次
特别的//就像模式串ADA,原串ADADADA,存在三次,明显有重叠,因此next函数就要多算一位。模式串长度为L,那么next函数不是计算到next[L-1],而是计算到Next[L]。
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
#define maxn 10001
char a[maxn],b[maxn];
int next[maxn];
void getnext(char b[],int next[])
{
int j,k;
j=0;k=-1;next[0]=-1;
while(j<strlen(b))
{
if(k==-1||b[j]==b[k])
{
j++;k++;
next[j]=k;
}
else k=next[k];
}
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%s%*c%s%*c",b,a);
int i=0,j=0,count=0;
getnext(b,next);
while(i<strlen(a))
{
if(j==-1||a[i]==b[j])
{
i++;j++;
}
else j=next[j];
if(j==strlen(b))
{
count++;j=next[strlen(b)];//????
}
}
printf("%d\n",count);
}
}