链接:点击打开链接
题意:求模式串在主串中出现次数
代码:
#include <map>
#include <set>
#include <queue>
#include <string>
#include <math.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int siz=1000005;
int nex[siz];
char S[siz],T[siz];
void getnex(int len){
int i,j;
j=-1,i=0;
nex[0]=-1;
while(i<len){
if(j==-1||T[i]==T[j])
nex[++i]=++j;
else
j=nex[j];
}
}
int kmp(int tlen,int slen){
int i,j,ans;
i=j=ans=0;
while(i<slen){
if(j==-1||S[i]==T[j])
i++,j++;
else
j=nex[j];
if(j==tlen){
i--;
j=nex[j-1];
ans++;
}
}
return ans;
}
int main(){ //kmp模板
int t,i,j;
scanf("%d",&t);
while(t--){
scanf("%s%s",&T,&S);
getnex(strlen(T));
printf("%d\n",kmp(strlen(T),strlen(S)));
}
return 0;
}