KMP算法

看了一晚上才算看明白,明天继续看

从头到尾彻底理解KMP

public class KmpSearch {
    public static int indexOf(String s, String p) {
        if (p.length() == 0) return 0;
        int[] next = new int[p.length()];

        getNext(p, next);

        int i = 0;
        int j = 0;
        int sLen = s.length();
        int pLen = p.length();

        while (i < sLen && j < pLen) {
            if (j == -1 || s.charAt(i) == p.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }

        if (j == pLen) {
            return i - j;
        } else {
            return -1;
        }
    }

    private static void getNext(String p, int[] next) {
        next[0] = -1;
        int j = 0;
        int k = -1;
        while (j < next.length - 1) {
            if (k == -1 || p.charAt(j) == p.charAt(k)) {
                j++;
                k++;
                next[j] = k;
            } else {
                k = next[k];
            }
        }
    }

    public static void main(String[] args) {
        int[] next = new int[5];
        getNext("ababc", next);
        System.out.println(indexOf("ababc","abc"));
    }
}

posted @ 2018-09-24 02:04  ACBingo  阅读(101)  评论(0编辑  收藏  举报