KMP
KMP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include<iostream.h> #include<string.h> #include<stdlib.h> typedef char sstring[256]; int next[8]; void getnext(sstring t,int next[]) { int i=1,j=0; next[1]=0; while(i<t[0]){ if(j==0||t[i]==t[j]){++i;++j;next[i]=j;} else j=next[j]; } } int indexkmp(sstring s,sstring t,int pos){ int i=pos;int j=1; while(i<=s[0]&&j<=t[0]){ if(j==0||s[i]==t[j]){++i;++j;} else j=next[j];} if(j>t[0])return i-t[0]; else return 0; } void main(){ int i,j; sstring s,t; for(i=1;i<=8;i++)cin>>s[i];s[0]=8; for(j=1;j<=3;j++)cin>>t[j];t[0]=3; getnext(t,next); cout<<indexkmp(s,t,1)<<endl; }
|