KMP算法,匹配字符串模板(返回下标)

    //KMP算法,匹配字符串模板
    void getNext(int[] next, String t) {
        int n = next.length;
        for (int i = 1, j = 0; i < n; i++) {
            while (j > 0 && t.charAt(i) != t.charAt(j)) {
                j = next[j - 1];
            }
            if (t.charAt(i) == t.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
    }

    int kmp(String s, String t) {
        int m = s.length(), n = t.length();
        if (n == 0)
            return 0;
        int[] next = new int[n];
        getNext(next, t);
        for (int i = 0, j = 0; i < m; i++) {
            while (j > 0 && s.charAt(i) != t.charAt(j)) {
                j = next[j - 1];
            }
            if (s.charAt(i) == t.charAt(j)) {
                j++;
            }
            if (j == n) {
                return i - n + 1;
            }
        }
        return -1;
    }
原文地址:https://www.cnblogs.com/wtao0730/p/15234665.html