Introduction to the KMP algorithm
The full name of the KMP algorithm is called Knuth-morris-pratt algorithm.
The string being searched is called the main string, and the strings to be searched are called pattern strings.
We know the naïve pattern matching algorithm: http://blog.csdn.net/chfe007/article/details/43448655 is very inefficient, the KMP algorithm starts from the pattern string and discovers the hidden information in the pattern string to reduce the number of comparisons. Specifically how to do this can be the link: http://kb.cnblogs.com/page/176818/
The key to the KMP algorithm is the derivation of the next array value .
Next array derivation
void GetNext (char *needle,int Len,int*Next) {inti =0, j =-1;Next[0] = -1; while(I <Len-1) {if(j = =-1|| Needle[i] = = Needle[j])Next[++i] = ++j;Elsej =Next[j]; } }
Improvement of next array derivation
void Getnextimp (char *needle,int Len,int*Next) {inti =0, j =-1;Next[0] = -1; while(I <Len-1) {if(j = =-1|| Needle[i] = = Needle[j]) {++i; ++j;Next[I] = (needle[i] = = Needle[j]?Next[j]: J); }Elsej =Next[j]; } }
KMP Algorithm Implementation
intStrStr (Char*haystack, Char*needle) {intHaystacklen = strlen (haystack);intNeedlelen = strlen (needle);int *next= newint[Needlelen];//GetNext (Needle, Needlelen,Next); Getnextimp (Needle, Needlelen,Next);inti =0, j =0; while(I < Haystacklen && J < Needlelen) {if(j = =-1|| Haystack[i] = = Needle[j]) {++i; ++j; }Else{j =Next[j]; } }returnJ >= Needlelen? I-needlelen:-1; }
Two of the string pattern matching algorithms: KMP algorithm