kmp存模板
求出现次数 不可重叠 (可重叠见注释)
推荐博客点击打开链接
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;
int nxtt[maxn],nxts[maxn];
char ch1[maxn],ch2[maxn];
void kmp(char *t,int lt)
{
int i,j;
nxtt[0]=-1;
i=0,j=-1;
while(i<lt)
{
if(j==-1||t[i]==t[j])
{
i++,j++;
nxtt[i]=j;
}
else j=nxtt[j];
}
}
int solve(char *s,int ls,char *t,int lt)
{
int res,i,j;
res=0,i=0,j=0;
while(i<ls){
if(j==-1||s[i]==t[j]){
i++,j++;
nxts[i]=j;
if(j==lt) res++,j=0;
//if(j==lt) res++,j=nxtt[j];
}
else j=nxtt[j];
}
return res;
}
int main()
{
int i,j;
while(scanf("%s%s",ch1,ch2)!=EOF)
{
if(ch1[0]=='#') break;
kmp(ch2,strlen(ch2));
printf("%d\n",solve(ch1,strlen(ch1),ch2,strlen(ch2)));
}
return 0;
}