KMP算法 next数组模板

        void preKMP(String s, int kmpNext[]) {
        int len = s.length();
        int k, j;
        k = kmpNext[0] = -1;
        j = 0;
        while (j < len - 1) {
            if (k == -1 || s.charAt(j) == s.charAt(k)) {
                if (s.charAt(++j) == s.charAt(++k)) {
                    kmpNext[j] = kmpNext[k];
                } else {
                    kmpNext[j] = k;
                }
            } else {
                k = kmpNext[k];
            }
        }
    }

表示匹配的时候,j 下次前移的位置

    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) return 0;
        int[] next = new int[needle.length()];
        preKMP(needle, next);
        int i = 0, j = 0;
        while (i < haystack.length() && j < needle.length()) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }
        if (j == needle.length()) {
            return i - j;
        } else {
            return -1;
        }
    }

 

posted on 2021-09-11 16:26  13rj1115  阅读(38)  评论(0编辑  收藏  举报

导航