KMP algorithm is an improved string matching algorithm, which is found by D.e.knuth and V.r.pratt and J.h.morris, so it is called the Knut-Morris-Pratt operation (the KMP algorithm).
The key of the KMP algorithm is to define a next function according to the given pattern string w1,m, and the next function contains the local matching information of the pattern string itself.
#include <iostream> #include <cstring> #include <string> #include <set> #include <map> Using namespace std;void buildpatchmatchtable (int *partmatchtable, char *findstr) {if (findstr = = NULL) return; Partmatchtable[0] = 0; int sizefind = strlen (findstr); for (int i = 1; i < Sizefind; ++i) {set<string> preset; String tmppre = ""; Tmppre = findstr[0]; Preset.insert (Tmppre); for (int j = 1; j < i; ++j) {tmppre = Tmppre + findstr[j]; Preset.insert (Tmppre); } set<string> Postset; String tmppost = ""; Tmppost = Findstr[i]; Postset.insert (Tmppost); for (int j = i-1; j > 0;--j) {tmppost = findstr[j] + tmppost; Postset.insert (Tmppost); } set<string> Comset; for (Set<string>::iterator beg = Preset.begin (); Beg! = Preset.end (); ++beg) {if (PostseT.count (*beg) > 0) comset.insert (*beg); } int maxlen = 0; for (Set<string>::iterator beg = Comset.begin (); Beg! = Comset.end (); ++beg) {if ((*beg). Size () ; MaxLen) MaxLen = (*beg). Size (); } Partmatchtable[i] = MaxLen; }}int KMP (Char *srcstr, char *findstr) {if (Srcstr = = NULL | | findstr = null) return-1; int lensrc = strlen (SRCSTR); int lenfind = strlen (findstr); int *partmatchtable = new Int[lenfind]; Buildpatchmatchtable (partmatchtable, findstr); for (int i = 0; i < lenfind; ++i) cout << findstr[i] << "\ t" << Partmatchtable[i] << Endl ; int curfind = 0; for (int i = 0; i < lensrc;) {if (findstr[curfind] = = Srcstr[i]) {++i; ++curfind; } else {if (Curfind = = 0) ++i; else {int movestep = Curfind-partmATCHTABLE[CURFIND-1]; i + = Movestep; Curfind = 0; }} if (Curfind = = lenfind) {delete []partmatchtable; return i-lenfind; }} return-1; delete []partmatchtable;} int main () {char srcstr[] = "Bbcabcdababcdabcdabde"; Char findstr[] = "ABCDABD"; cout << "POS:" << kmp (Srcstr, findStr) << Endl; Char srcstr2[] = "substring searching algorithm search"; Char findstr2[] = "search"; cout << "POS:" << kmp (SRCSTR2, findStr2) << Endl;}
C + + KMP algorithm