KMP算法

2019-06-19  本文已影响0人  RalapHao
  1. 根据部分匹配表,完成跳跃式的比较匹配
public class KmpAlgorithm {

    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        KmpAlgorithm ha = new KmpAlgorithm();
        int[] ints = ha.kmpNext(str2);
        System.out.println(Arrays.toString(ints));
        System.out.println(ha.serach(str1, str2, ints));
    }
    /**
     * 获取部分匹配值表
     */
    public int[] kmpNext(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length(); i++) {
            //如果不相等,根据next匹配表获取新值
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public int serach(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            //根据部分匹配表调整跳转位数
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }
}

上一篇下一篇

猜你喜欢

热点阅读