KMP算法Java代码实现

  

  KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现,因此人们称它为克努特——莫里斯——普拉特操作(简称KMP算法)。KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,
函数本身包含了模式串的局部匹配信息。时间复杂度O(m+n)。

import java.util.Arrays;

public class Test {

    /**
     * @param str 文本串
     * @param dest 模式串
     * @param next 匹配核心数组
     * @return
     */
    public static int kmp(String str, String dest,int[] next) {
        for(int i = 0, j = 0; i < str.length(); i++){
            if (j > 0 && str.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (str.charAt(i) == dest.charAt(j)) {
                j++;
            }
            if (j == dest.length()) {
                return i-j+1;
            }
        }
        return 0;
    }

    public static int[] kmpnext(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for(int i = 1,j = 0; i < dest.length(); i++) {
            if (j > 0 && dest.charAt(j) != dest.charAt(i)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static void main(String[] args){
        String a = "ABABAE";
        String b = "ABABABABAEBEABADAEABAEABABAE";
        int[] next = kmpnext(a);
        System.out.println(Arrays.toString(next));
        int res = kmp(b, a,next);
        System.out.println(res);
    }

}

  

猜你喜欢

转载自www.cnblogs.com/loytime/p/10451509.html
今日推荐