其他分享
首页 > 其他分享> > 剪花布条(KMP

剪花布条(KMP

作者:互联网

#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;
    }
	
}

标签:nxt,string,int,布条,KMP,剪花,++,ans,pi
来源: https://blog.csdn.net/weixin_45714303/article/details/119464940