KMP algorithm is an algorithm used to find the occurrence and position of substring B of a string;
Look at a link before you look at the back https://kb.cnblogs.com/page/176818/
And then there's an approximate understanding of the algorithm.
In order to implement this algorithm we need a next array, that is, a partial match table in the link just now, Next[i] represents the longest length of ' B ' that is the prefix of the non-prefix substring ' and ' B ' that is terminated by ' I ';
such as: Abababaac i=7 for the end of the ' non-prefix substring ' has 6, respectively, is 2~7,3~7,4~7,....,7~7;
If B "2~7" = ' Bababa ' does not match the prefix ' Ababab '
B "3~7" = ' Ababa ' matches the prefix ' Ababa ', with a length of 5;
.............
Draw Next "7" = 5;
But how to find the next array we can assume that next "1~6" has been found out. Next "6" = 4; and b "3~6" and B "1~4" match;
Next, B "7" =b "5" = ' A ', so B "7" = 5; happy, next match;
But when next "8", B "8" = ' A ' B "6" = ' B ' does not match;
So we have to shorten the matching length, that is, we have i=7 to wade match length out of 5, there is b[5~7] "B" in the length of "3" match; B "1" to B "7" for the length of 1;
We try to match whether these two matches make i=8;
But B "8" in B "4", B "2" is not equal, so we can only let i=8 punch start to match, B "1" happens to B "8" match; so next "8" = 1;
How do we remember the road 5,3,1 these matching lengths?
First Next "7" = 5; description from i=7 forward 5 characters to the B "the" is equal.
This is what we define a J; to match the J-character from 5 to the B "1~j"; What do you mean, 5 is next "5"; (Don't forget the next array definition);
When the J=next "5" = 3, the next one to find is next "3";
So the code is there (probably not yet, just look at the code)
1. Initialize Next "1"=j=0, assuming next "1~i-1"We are seeking the next" I ". 2Try to match the next bit, if the match fails, it makes J=next "J" (which says why). Until j=0;3If it matches, it j+.1, Next "I" =j;next[1]=0; for(intI=2, j=0; I<=strlen (a); + +i) { while(j>0&& a[i]!=a[j+1]) j=next[j];////Match failed if(a[i]==a[j+1]) J + +;///Match Successnext[i]=J;}
And then with the next array, you can KMP.
for (int i=1, j=0; I<=strlen (b); + +i) {while (j>0 & & (J==n | | b[i]!=a[j+1]) j=next[j]; if (b[i]==a[j+1]) j + +; if /// at this point the match position is I-strlen (a) +1}
And then it was gone;
String Algorithm ①--KMP