kmp算法java

KMP 是三位大牛:D.E.Knuth、J.H.Morris 和 V.R.Pratt 同时发现的。其中第一位就是《计算机程序设计艺术》的作者!!

KMP 算法要解决的问题就是在字符串(也叫主串)中的模式(pattern)定位问题。说简单点就是我们平时常说的关键字搜索。模式串就是关键字(接下来称它为 P),如果它在一个主串(接下来称为 T)中出现,就返回它的具体位置,否则返回-1(常用手段)。

    public static void main(String[] args) {
        kmp("ababacabababca", "abababca");
    }

    private static int kmp(String s, String p) {
        int[] pmt = generatePmt(p);
        int tar = 0, pos = 0;
        while (pos < pmt.length) {
            if (s.charAt(tar) == p.charAt(pos)) {
                tar++;
                pos++;
            } else if (pos != 0)
                pos = pmt[pos - 1];
            else
                tar++;

            if (pos == p.length())
                return tar - pos;
        }
        return -1;
    }

    private static int[] generatePmt(String p) {
        int[] pmt = new int[p.length()];
        int x = 1;
        int now = 0;

        while (x < p.length()) {
            if (p.charAt(now) == p.charAt(x)) {
                now++;
                pmt[x] = now;
                x++;
            } else if (now != 0)
                now = pmt[now - 1];
            else {
                pmt[x] = 0;
                x++;
            }
        }
        return pmt;
    }
posted @ 2024-05-22 10:13  dkpp  阅读(9)  评论(0编辑  收藏  举报