In front of the KMP algorithm to do a variety of explanations, now the algorithm to do a code implementation:
intKmpsearch (Char*s,Char*p) { inti =0; intj =0; intSlen =strlen (s); intPlen =strlen (P); while(I < Slen && J <Plen) { //If J =-1, or if the current character matches successfully (that is, s[i] = = P[j]), make i++,j++ if(j = =-1|| S[i] = =P[j]) {i++; J++; } Else { //if J! =-1, and the current character match fails (that is, s[i]! = P[j]), then I is unchanged, j = Next[j]//Next[j] is the next value corresponding to Jj =Next[j]; } }// while if(J = =Plen) { returnIJ; } Else { return-1; }}
Time complexity analysis of KMP algorithm:
If the length of the text string is n and the length of the pattern string is M, then the time complexity of the matching process is O (n), which calculates the O (m) time of next, and the overall time complexity of the KMP is O (M + N).
An understanding of the KMP algorithm (vi)