#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
vector<int> nxt;string s,t;
int n;int ans=0,pre=-1;
vector<int> getnxt(string s) {
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) j = pi[j - 1];
if (s[i] == s[j]) j++;
pi[i] = j;
}
return pi;
}
void KMP_Count(string s,string p) {//x为模式串
int m=s.size(),n=p.size();
for(int i = 0, j = 0; i < m; ++i){
while(j && s[i] != p[j]) j = nxt[j-1];
if(s[i] == p[j]) j++;
if(j == n){
// cout<<i-n+1<<endl;
if(i-n+1>pre) ans+=1,pre=i;
j = nxt[j-1];
}
// cout<<pre<<endl;
}
}
int main(){
while(1){
cin>>s>>t;
ans=0;pre=-1;
if(s[0]=='#') return 0;
nxt=getnxt(t);
KMP_Count(s,t);
printf("%d\n",ans);
// for(int i=0;i<t.size();i++){
// cout<<nxt[i]<<" ";
// }cout<<endl;
}
}
剪花布条(KMP
最新推荐文章于 2021-08-23 23:45:18 发布