#include <iostream>
#include <stdio.h>
#include <queue>
#include <algorithm>
#include <string>
#include <cstring>
#include <climits>
using namespace std;
const int maxm=1000+10;
string w,t;
int nexta[maxm];
void nextaa()
{
int i,j;
j=-1;
nexta[0]=-1;
while(i<t.size())
{
if(j==-1 || t[i]==t[j])
{
if(t[i+1]==t[j+1]) nexta[++i]=nexta[++j];
else nexta[++i]=++j;
}
else j=nexta[j];
}
return;
}
int kmp()
{
int cmp=0;
nextaa();
int i,j;
i=j=0;
while(i<w.size())
{
if(j==-1 || w[i]==t[j]){i++;j++;}
else{j=nexta[j];}
if(j==t.size()){cmp++;j=0;}
}
return cmp;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while(cin>>w && w[0]!='#')
{
cin>>t;
int ans=kmp();
cout<<ans<<endl;
}
return 0;
}
AC代码如上。
刚好是我上次做的KMP的题目错了的地方哈哈哈,然后就是这题的小变动。
求得是不重叠的字符串~