首页 > 代码库 > kmp单次匹配

kmp单次匹配

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 int i,j,ls,lp,next[10000];
 5 string s,p;
 6 int main()
 7 {
 8     ios::sync_with_stdio(false);
 9     //cin>>ls>>lp>>s>>p;
10     cin>>s>>p;ls=s.length();lp=p.length();
11     i=0,j=-1;
12     next[0]=-1;
13     while(i<lp-1)
14         if(j<0||p[i]==p[j])
15         {
16             i++;j++;
17             if(p[i]!=p[j]) next[i]=j;else next[i]=next[j];
18         }else j=next[j];
19     i=0,j=0;
20     while (i<ls&&j<lp)
21         if (j<0||s[i]==p[j]) {i++;j++;}else j=next[j];
22     if (j==lp) cout<<i-j+1<<endl;else cout<<"0"<<endl;
23 }

 

kmp单次匹配