字符串匹配算法-kmp

kmp算法适合大字符串的对比匹配

kmp 核心,获取模式串回溯索引数组

    private static int[] getNext(String needle) {
        int length = needle.length();
        char[] chars = needle.toCharArray();
        int [] next = new int[length];
        // 初始化查找字符串索引数组,没有上级映射为-1
        next[0] = -1;
        int pre = -1;
        int i = 0;
        while (i < length - 1) {
            if (pre == -1 || chars[pre] == chars[i]) {
                next[++i] = ++pre;
                // 优化 当下一组索引对比也相同,当前索引取上一组索引的值
                if (chars[i] == chars[pre]) {
                    next[i] = next[pre];
                }
            } else {
                pre = next[pre];
            }
        }
        return next;
    }

字符串对比

    //    kmp算法 查找字符串
    public static int kmpIndexOf(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        char[] h = haystack.toCharArray();
        int hl = haystack.length();
        char[] n = needle.toCharArray();
        int nl = needle.length();
        int[] next = getNext(needle);
        //开始匹配
        // 主串位置
        int i = 0;
        // 模式串位置
        int j = 0;
        while (i < hl && j < nl) {
            if (j == -1 || h[i] == n[j]) {
                i++;
                j++;
            } else {
                // 模式串回溯
                j = next[j];
            }
        }
        // 匹配成功
        if (j >= nl) {
            return i - nl;
        }
        // 匹配失败
        return -1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值