When the substring is aaaab, there will be unnecessary backtracking.
Because the next array is 01234 at this time, if the main string s [I]! = T [4], J values are traced back in sequence, but the first four are all identical characters, so tracing of J values is unnecessary.
That is to say, when the substring has repeated characters, the value in the next array corresponding to it only needs to be the same as the value recorded in the next array when it first appeared. For example, for a substring 'A', 'B ', 'A', 'B', 'A', 'C', 'A', 'c'. The improved next array should be 010104102
New next array generationCode:
Void get_nextval (char * t, int * Next) {int I, j; I = 1; j = 0; next [I] = 0; while (I <t [0]) {If (j = 0 | T [I] = T [J]) {++ I; ++ J; if (T [I]! = T [J]) {next [I] = J;} else {next [I] = next [J];} else {J = next [J] ;}}
KMP Code only needs to replace get_next (T, next); with get_nextval (T, next );
010104102