KMP算法(非递归)

public class KMP {
    //str文本串  dest 模式串
    public static boolean kmp(String str, String dest, int[] next) {

        int strBegin = 0;
        int index = 0; //已匹配的字符数
        int nos = 0;// 移动位数 = 已匹配的字符数 - 对应的部分匹配值
        while(strBegin < str.length()){
            char strChar = str.charAt(strBegin);
            char destChar = dest.charAt(index);
            if(strChar == destChar){
                index++;
                if(index==dest.length()){
                    return true;
                }
                strBegin++;
            }
            if(strChar != destChar)
            {
                if(index > 0){
                    nos = index-next[index-1];
                    strBegin+=nos;
                }else {
                    strBegin++;
                }
                index = 0;
            }
        }
        return false;
    }

    public static int[] next(String dest) {
        int[] next = new int[dest.length()];
        for (int i = 1; i < dest.length() + 1; i++) {
            String index = dest.substring(0, i);
            String[] prefix = new String[index.length() - 1];
            String[] suffix = new String[index.length() - 1];
            if (index.length() < 2) {
                continue;
            } else {
                for (int j = 1; j < index.length(); j++) {
                    prefix[j - 1] = index.substring(0, j);
                }
                for (int j = index.length() - 1; j > 0; j--) {
                    suffix[j - 1] = index.substring(j, index.length());
                }
            }
            next[i - 1] = compare(prefix, suffix);
        }

        return next;
    }

    public static int compare(String[] prefix, String[] suffix) {
        int count = 0;
        for (int i = 0; i < prefix.length; i++) {
            for (int j = 0; j < suffix.length; j++) {
                if (prefix[i].equals(suffix[j])) {
                    count = prefix[i].length();
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String dest = "QWERQWR";
        String str = "WWE QWERQW QWERQWERQWRT";
        int[] next = next(dest);
        System.out.println(Arrays.toString(next));
        boolean b = kmp(str,dest,next);
        System.out.println(b);
    }
}


部分匹配表,即next数组参考自:[字符串匹配的KMP算法](http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值