Last vacation to learn KMP, but basic not, so forget clean ... The core idea of this is next array, next array called longest same prefix suffix. It's a good algorithm, KMP.
The matching process is more than the original violence match a jump to jump to the next.
Here is a link: From beginning to end KMP, write very good, very understood!
Paste the Board code: (self-written comments, may not be, welcome to point out)
#include <cstdio>#include<cmath>#include<cstring>using namespacestd;intnext[1000005];Chars[1000005];//S is a matching stringChart[1000005];//T is a text stringintans[1000005];//Record AnswersintMain () {scanf ("%s%s", T +1, S +1);//starting from 1 to save intls = strlen (s +1); intlt = strlen (t +1); intK =0;//k is the maximum number of suffixes to matchnext[1] =0; for(inti =2; I <= ls;i++)//start matching S, build next array { while(k! =0&&s[i]! = s[k +1])//suffix is not equal then return to Next[k]K =Next[k]; if(S[i] = = S[k +1]) k++;//suffix equalNext[i] =K; } k=0; intnum =0; for(inti =1; I <= lt;i++)//start matching text string { while(k! =0&&t[i]! = s[k +1]) K=Next[k]; if(T[i] = = S[k +1]) k++; if(k = = ls)//if the text string is already matched to S, record the answer{num++; Ans[num]= I-ls +1; } } for(inti =1; I <= num;i++) printf ("%d\n", Ans[i]); for(inti =1; I <= ls;i++) printf ("%d", Next[i]);//Output Answer return 0;}
KMP Character matching algorithm