This algorithm is a leader in the string matching algorithm. It only uses the time of O (lengthText + lengthPattern) to complete the matching task. The reason for his speed is that there is no need to trace back. The most profound and difficult part of this algorithm is that the two strings are matched, and the success or failure is only related to the template string and the target string. If the template string fails to match in the j position, you do not need to re-enter the 0 position. The next position should be next [j. The following is the function for generating the next array: [cpp] void GetNext (string Pattern, vector <int> & next) {int j = 0; int k =-1; int lenP = Pattern. length (); next. assign (8,-1); while (j <lenP) {if (k =-1) | (Pattern [j] = Pattern [k]) {j ++; k ++; next [j] = k;} else {k = next [k] ;}} below is the KMP algorithm: [cpp] int KMP (string Text, string Pattern, vector <int> & next, int TdefPos = 0) {int posP = 0, posT = TdefPos; int lenP = Pattern. length (); int lenT = Text. length (); while (posP <lenP) & (posT <lenT) {if (posP =-1) | Pattern [posP] = Text [posT]) {posP ++; posT ++;} else {posP = next [posP] ;}} if (posP <lenP) {return-1;} else {return (lenT-lenP );}}