首页 > 算法 > KMP算法

KMP算法

作者:bin

next求解的代码,目的是找到当前i位置,如果下一个不匹配,需要回溯到哪里

String str = "ababaa";

char[] chars = str.toCharArray();
int next[] = new int[chars.length];
int i = 0;
int j = -1;
next[0] = -1;
while (i < chars.length - 1){
    if (j == -1 || chars[i] == chars[j]){
        ++j;
        ++i;
        next[i] = j;
    }else {
        j = next[j];
    }
}

System.out.println(next);

图解:

您必须 [ 登录 ] 才能发表留言!