A few days ago wrote a KMP algorithm blog post, on the data structure of the KMP (pattern matching algorithm in the string), in this article, talked about a pattern string K value of the record array
Next[], in detail to see that article, in fact, the previous definition of the next[] array is a certain flaw, below me I will be an example of a situation:
For example, if the next[] array is obtained by the previous method, when the two strings match, the situation will appear as follows:
We find that the road from Step1 to Step3 is wasteful because it is compared with the same letter (a) and B, and this computer is hum-easy to recognize, so for
The improvement of next[] is a line of work.
The reason why I would say that the above 3 steps is white walk, think this is three consecutive equal a, so we can jump from the first step to the fourth step, namely: The resulting array next[j] = k, and the pattern string p[j] = P[k], when the main string s[i] and P[j] match failed, Do not need to compare with p[k], but direct and P[next[k]], of course, can always iterate forward.
That
The code is as follows:
void Get_nextval (Sstring T,IntNextval[]) {int i =1, j =0 Nextval[1] = 0; while (i <= t[0if (j = = 0 | | T[i] == T[j]) {j++if (Nextval[i] == Nextval[j]) {nextval[i] = NEXTVAL[J]; } else J;}} else {J = Nextval[j];}}
KMP algorithm from next[] to nextval[] (RPM)