#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int dmax=1000100;
char s[dmax],p[dmax];
int next[dmax];
void get_next(char *p){
int k=-1,j=0,n=strlen(p);
next[0]=-1;
while (j<n){
if (k==-1 || p[k]==p[j]){
k++;
j++;
if (p[j]!=p[k])
next[j]=k;
else next[j]=next[k];
}else k=next[k];
}
}
int kmp(char *s,char *p){
int i=0,j=0,x=strlen(s),y=strlen(p),ans=0;
get_next(p);
while (i<x){
if (j==y){
ans++;
j=next[j];
}
if (j==-1 || s[i]==p[j]){
i++;
j++;
}else j=next[j];
}
if (j==y)
ans++;
return ans;
}
int main(){
int T;
scanf("%d",&T);
getchar();
while (T--){
memset(p,0,sizeof(p));
memset(s,0,sizeof(s));
memset(next,0,sizeof(next));
gets(p);
gets(s);
printf("%d\n",kmp(s,p));
}
return 0;
}
POJ3461 KMP快速字符串匹配
最新推荐文章于 2020-03-26 03:56:14 发布