/** KMP pattern matching algorithm */# include <iostream> # include <cstring> using namespace STD;/** calculate the next array of the mode string, another mode string is used for matching * the time complexity is O (M), and m is the length of the mode string */void countnext (char * strpattern, int Len, int * Next) {int I = 0, j =-1; next [I] = J; while (I <len-1) {If (j =-1) {I ++; j ++; next [I] = J;} else if (strpattern [I] = strpattern [J]) {I ++; j ++; if (strpattern [I]! = Strpattern [J]) {next [I] = J;} else {next [I] = next [J] ;}} else {J = next [J] ;}}/ ** use the KMP algorithm to perform mode matching. * The time complexity of the KMP algorithm is O (n) + O (m) = O (N + M) * where N is the length of the Main string, M is the length of the mode string, you need to first calculate the next array * the core of the KMP algorithm is that in the process of searching the mode string, the pointer of the Main string will not go back * It will be moved as far as possible to avoid invalid rollback, saves time and is suitable for the case where many matching mode strings exist in the main string *. Otherwise, if there is no rollback, KMP algorithm is not required */INT indexkmp (char * strmain, int lenmain, char * strpattern, int lenpattern, int POs, int * Next) {int I = POs, j = 0; while (I <lenmain & J <lenpattern) {If (j =-1 | strmain [I] = strpattern [J]) {I ++; j ++ ;} else {J = next [J] ;}} if (J >= lenpattern) {return I-lenpattern ;}return-1 ;} int main () {char * strpattern = "abce"; char * strmain = "ksekabcedwfabcekf"; int lenmain = strlen (strmain); int lenpattern = strlen (strpattern ); int * Next = new int [lenpattern]; countnext (strpattern, lenpattern, next); int startpos = 5; int Pos = indexkmp (strmain, lenmain, strpattern, lenpattern, startpos, next); If (Pos <0) {cout <"from string" <strmain <"'s" <startpos + 1 <"The position does not contain the string" <strpattern <Endl ;} else {cout <"from the string" <strmain <"of the" <startpos + 1 <"position start to find the string" <strpattern <"in" <POS + 1 <"positions" <Endl ;} delete [] Next; return 0 ;}
Pattern Matching KMP Algorithm