The KMP algorithm is a major improvement to the string matching algorithm. It uses the characteristics of the substring to improve the algorithm efficiency.
The key or essence of the KMP algorithm is the computation with next.
Assume that the primary string S and the sub-string T exist. In a match, we find T (k )! = S (I + 1)
Then we get a matching result.
That is: T (1) ...... T (k-1) = S (I-k + 1) ...... S (I-1)
Let's assume that there is a j <k making: T (1 )...... T (J-1) = S (I-k + 1 )..... S (I-k + J-1)
That is to say T (1) ...... T (J-1) = T (k-j) ...... T (k-1)
Therefore, we need to move the substring to the right k-j bit. If this is not the case, that is, j = 0, then we need to move the k-bit to the right.
Therefore, we only need to find the j corresponding to each position in the substring.
This is the idea of the KMP algorithm.
Therefore, the next () function is defined as follows:
0 j = 1
Next () = max (k/1 <= k
1 If the above K does not exist and T (1 )! = T (j)
0 if the above K does not exist and T (1 )! = T (I)
The code for finding the next () function is as follows:
Char s [100]; // The matched string char t [100]; // The matched string int next [100]; // store the int s_length, t_length, and the distance between each character in the matching string. // The length of the character void getnext () {int I = 0, j =-1; next [I] =-1; while (I <t_length) {while (j> = 0 & t [I]! = T [j]) j = next [j]; // compare it with the character before the character to see if it is the same as the character before I ++; j ++; if (t [I] = t [j]) next [I] = next [j]; // if the current two characters are the same, else next [I] = j ;} for (I = 0; I <t_length; I ++) printf ("% d \ n", next [I]) ;}// the sliding distance to the right is: j-next [j]