There must be a lot of people on the KMP algorithm, learned many times, or do not understand, in fact, very simple, we simply look at two problems, you can!
General violence algorithm, everyone, should know, sweep two times, direct comparison, you can get the answer,
We see directly, there is no simplification
First, the same as the general algorithm, directly match, until P[i]!=p[j]; At this time, if the general algorithm I want to back back, J also to start again, but we did not make good use of the useful information has been obtained
Already know, the preceding paragraph is equal, we can think of a way, do not let I move, direct comparison, this is some, if we know, J Front string, the maximum prefix equals suffix, is the mark A is equal,
Then, do not move I, directly compare p[i]==p[next[j]], you can!
In this way, the next array is introduced, the next array, simple point, is the maximum prefix equals suffix, is required to the maximum length of a, you can!
So how to find the maximum length of a, look at this figure
If p[i-1] = = P[k], then we can directly get next[i]= next [i-1]+1;
If, not equal, we can use a recursive derivation,
, we know, p[i-1]! = P[k]; But we also know useful information A0 A1 A2 is the same string!
At this point, we put k = Next[k], then, according to the definition of the next array, we know that B0 B1 B2 B3 B4 B5 are the same, then, we just compare p[i-1] = = P[next[k]], can be obtained next[i-1], of course, if not equal, Then k = next [K], so that, to be sure, find the beginning of the end of the point, you can get the answer!
I learn KMP is also do not understand why, so always forget, since the drawing of these two pictures, no longer have to recite the code, you can write it out, so I hope readers, understand the two map, naturally understand the KMP algorithm!
KMP Algorithm Summary