64,676
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<string>
using namespace std;
int * next(char *temp)
{
int i,j;
int *next = new int[ strlen(temp) ];
next[0]=-1;
for(i=1; i < strlen(temp); i++)
{
j=next[i-1];
while(j>=0 && temp[i] != temp[j+1])
j=next[j];
if(temp[i]==temp[j+1]) next[i]=j+1;
else next[i]=-1;
}
return next;
}
void KMP(char* a,char *b,int *next)
{
int i=0,j=0;
int n=0;
while(i<strlen(a))
{
while(i<strlen(a) && j<strlen(b))
{
if(a[i]==b[j])
{
i++;j++;
}
else if(j==0) i++;
else j = next[j-1] + 1;
}
if(j>=strlen(b)) //匹配啦
{
n++;
i = i - next[j-1] - 1;
j=0;
}
}
printf("%d\n" ,n);
}
int main()
{
char a[10001];
char b[1000001];
int t;
cin>>t;
for(;t>0;t--)
{
cin>>a>>b;
KMP(b,a, next(a) );
}
return 0;
}