//============================================================================ // Name : c++KMP.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include<string> using namespace std; void getNext(string T,int next[],int length) { next[1]=0; int i=1; int j=0; while(i<length) { if(j==0||T[i]==T[j]) { i++;j++;next[i]=j; } else j=next[j]; } for(int i=1;i<=length;i++) { cout<<next[i]<<" "; } cout<<endl; } void getNextval(string T,int nextval[],int length) { nextval[1]=0; int i=1;int j=0; while(i<length) { if(j==0||T[i]==T[j]) { i++;j++; if(T[i]!=T[j]) nextval[i]=j; else nextval[i]=nextval[j]; } else j=nextval[j]; } for(int i=1;i<=length;i++) { cout<<nextval[i]<<" "; } cout<<endl; } int Index_Kmp(string s,string T,int pos,int *next) { int i=pos; int j=1; while(i<=s.length()-1&&j<=T.length()-1) { if(j==0||s[i]==T[j]) { i++;j++; } else { j=next[j]; } } if(j>T.length()-1) return i-(T.length()-1); else return -1; } int main() { int next[100]; int nextval[100]; string T="0abaabcac"; string s="0acabaabaabcacaabc"; getNext( T, next,T.length()-1); getNextval( T, nextval,T.length()-1); cout<<Index_Kmp( s, T, 1,nextval)<< endl; return 0; }