上篇说到当子串为aaaab类似情况时,会有不必要的回溯
因为此时next数组为01234,如果主串S[i] != T[4]时,j值依次回溯,可是前四个都是完全一样的字符,所以j值的回溯是没有必要的
也就是说,在满足上一篇next数组的条件下,当子串有字符重复时,它所对应的next数组中的值只需要与它第一次出现时的在next数组中记录的值一样即可,比如,对于一个子串'a', 'b', 'a', 'b', 'a', 'c', 'c', 'a', 'c',改进后的next数组应该为010104102
新的next数组生成代码:
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代码只需把get_next(T, next);替换成get_nextval(T, next);
010104102