字符串 abcd abc abcd abc
匹配串 cdabcd
匹配串的 next 0 0 0 0 1 2;
开始匹配
abcd abc abcd abc
cd abc d
a,d 匹配失败
next 数组进行移动
abcd abc abcd abcd
c dabcd
再次匹配
模板
这个算法有些问题(尚未找到修改方法)
#include<bits/stdc++.h> using namespace std; const int maxn=1e5+10; int nt[1000]; // next 数组首位为 0 int KMP(string ss,string tt) { nt[0]=0; for(int p=1,k=0;p<tt.size();p++) { while(k>0 && tt[k]!=tt[p]) k=tt[k-1]; if(tt[k]==tt[p]) k++; nt[p]=k; } // 构建 next 数组 for(int p=1,k=0;p<ss.size();p++) { while(k>0&& ss[p]!=tt[k]) k=tt[k-1]; if(ss[p]==tt[k]) k++; if(k==tt.size()) { cout<<"数组下标开始"<<p-tt.size()+1<<" "<<p<<endl; return 1; } } return 0; } int main() { string ss,tt; cin>>ss>>tt; cout<<KMP(ss,tt)<<endl; }
next[0]=-1;
#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int nt[10005]; char tt[1000005]; char ss[1000005]; int KMP() { int s=strlen(ss); // ss int t=strlen(tt); nt[0]=-1; int num=0; for(int i=0,j=-1;i<s;) { if(j==-1||ss[i]==ss[j]) { i++; j++; nt[i]=j; // next[1]=0; } else j=nt[j]; } //for(int i=0;i<s;i++) //cout<<nt[i]<<endl; for(int i=0,j=0;i<t;) { if(j==-1||ss[j]==tt[i]) { i++; j++; } else j=nt[j]; if(j==s) { num++; j=0; } } return num; } int main() { while(scanf("%s",tt)!=EOF&&tt[0]!='#') { scanf("%s",ss); cout<<KMP()<<endl; } }