字符串 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; ; ]; // next 数组首位为 0 int KMP(string ss,string tt) { nt[]=; ,k=;p<tt.size();p++) { && tt[k]!=tt[p]) k=tt[k-]; if(tt[k]==tt[p]) k++; nt[p]=k; } // 构建 next 数组 ,k=;p<ss.size();p++) { && ss[p]!=tt[k]) k=tt[k-]; if(ss[p]==tt[k]) k++; if(k==tt.size()) { cout<<<<" "<<p<<endl; ; } } ; } 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 KMP() { int s=strlen(ss); // ss int t=strlen(tt); nt[]=-; ; ,j=-;i<s;) { ||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; ,j=;i<t;) { ||ss[j]==tt[i]) { i++; j++; } else j=nt[j]; if(j==s) { num++; j=; } } return num; } int main() { ]!='#') { scanf("%s",ss); cout<<KMP()<<endl; } }