I watched KMP for two nights and added the basic "brute force matching"
When I understood next [J] recursive solution tonight, I suddenly felt that the algorithm was really wonderful. Although the consciousness was late, it was better than never!
My blogs are both trial study notes and are not instructive. They are well written by the experts, such as July and matrix67 blogs. (today I know the legend of matrix67)
[Stick to the top] thoroughly understand KMP from start to end (version August 22, 2014)
[Stick to the top] thoroughly understand KMP from start to end (version August 22, 2014)
I have resigned from my internship. I can read books and find a job with all my heart. It's really good to be free !! For the sake of our future together !!
It's not too late to work at any time. Despite some twists and turns in my way, this chicken soup has filled me so well!
Today, cainiao won't be a cainiao for tomorrow ......
Problems faced by KMP: long strings (text strings) are s strings, short strings (pattern strings) are P strings, and determining whether a p string is a substring of S, if the starting position of P in S is found
S string index I
P string index J
KMP idea: (assuming we have learned about the "brute force matching" algorithm)
① When P0, P1 ...... PJ-1 and Si-J, Si-J + 1 ,...... The Si-1 matches, but PJ! = Si, J does not have to return to 0 to start matching
② It is to analyze the properties of the P string so that "J does not trace back", which is related to the value of the next [J] array.
③ ...... (It turns out that reading and writing are not a field. The Library is about to close. First, write it here)
Add your own implementation code
# Include <iostream> # include <string> using namespace STD; // KMP algorithm to analyze the nature of the short string P and find the "Longest string with prefix = suffix ", so that the index J goes back less void getnext (char * P, int next []) {int K =-1; Int J = 0; next [0] =-1; int Plen = strlen (p); While (j <pLen-1) {If (k =-1 | P [k] = P [J]) {J ++; k ++; next [J] = K;} else K = next [k]; // This is a bit obscure, but it is exactly the essence of recursion} int kmpsearch (char * s, char * P) {int I = 0, j = 0; int slen = strlen (s ); int Plen = strlen (p); int * Next = new int [Plen]; getnext (p, next); While (I <slen & J <Plen) {If (j =-1 | s [I] = P [J]) // here J =-1 does not understand {I ++; j ++;} else J = next [J];} Delete next; If (j = Plen) return I-j; else return-1;} int main () {char * S1 = "BBC abcdab abcdabcdabde"; char * S2 = "abcdabd"; cout <kmpsearch (S1, S2) <Endl; return 0 ;}
[Basic algorithm] String Matching Algorithm for KMP text string mode strings