题目:http://acm.hdu.edu.cn/showproblem.php?pid=2087
题目大意 :给两个串,看第二个串在第一个串中出现多少次
思路:一般kmp的做法在str2匹配完后就他跳出循环,这时候把跳出循环改成str2从头继续匹配即可。
#include<bits/stdc++.h>
using namespace std;
char T[100000],t[100000];
int nex[100000],res=0,ans=0;
void getnext(){
int len=strlen(t);
int j=0,k=-1;
nex[0]=-1;
while(j<len)
if(k==-1||t[j]==t[k])nex[++j]=++k;//如果匹配成功 next的下一个就等于匹配成功的下一个
else k=nex[k]; //匹配失败不断寻找有相同前缀的
}
void solved(){
int lenT=strlen(T);
int lent=strlen(t);
int i=0,j=0;
res=ans=0;
while(i<lenT&&j<lent){
if(j==-1||T[i]==t[j]){
i++;j++;
}else j=nex[j];
if(j==lent){
res++;j=0;
}
}
}
int main(){
scanf("%s",T);
while(T[0]!='#'){
scanf("%s",t);
getnext();
solved();
printf("%d\n",res);
scanf("%s",T);
}
return 0;
}