//简单的kmp匹配,寻找子串的个数,找到一个之后移动相应的指针就行了
#include<iostream>
using namespace std;
char a[1005];
char b[1005];
int next[1005];
void get_next(char const* ptrn,int plen,int* next){
int i=0;
next[i]=-1;
int j=-1;
while(i<plen-1){
if(j==-1||ptrn[i]==ptrn[j]){
++i;
++j;
next[i]=j;
}else{
j=next[j];
}
}
}
int kmp_search(char const* src,int slen,char const* patn,int plen,int const* next,int pos)
{
int i=pos;
int j=0;
while(i<slen&&j<plen){
if(j==-1||src[i]==patn[j]){
++i;
++j;
}else{
j=next[j];
}
}
if(j>=plen)
return i-plen;
else
return -1;
}
int main(){
while(scanf("%s%s",a,b)&&strcmp(a,"#")!=0){
int len1=strlen(a);
int len2=strlen(b);
int res=0;
get_next(b,len2,next);
int pos=0;
while(pos<len1){
int move;
if((move=kmp_search(a,len1,b,len2,next,pos))!=-1){
res++;
pos=move+len2;
}
else
break;
}
cout<<res<<endl;
}
return 0;
}
hdu 2087 kmp
最新推荐文章于 2022-04-20 23:46:23 发布