KMP算法

class Solution {
    /**
        KMP算法,模式串匹配,构建next数组,不用每次都返回起点开始比较,原O(m*n),KMP O(m+n)
    */
    public int strStr(String haystack, String needle) {
        int nh = haystack.length();
        int nn = needle.length();
        if(nn == 0) return 0;

        // 构建next数组
        int[] next = new int[nn];
        for(int i = 1,j = 0;i < nn;i++){
            // 不等的回溯
            while(j > 0 && needle.charAt(i) != needle.charAt(j)){
                // 为什么回溯j-1呢?因为j这个点已经不相等了,通过next[j]回溯都是相等的,所以看前边有没有相等的,没有就再往前,直到为0
                j = next[j-1];
            } 
            // 如果相等就同步++,此处j++就行了,i在for循环会自增
            if(needle.charAt(i) == needle.charAt(j)) j++;
            // 最后j回溯到哪个位置,就赋值
            next[i] = j;
        }

        // 开始匹配
        for(int i = 0,j = 0;i < nh;i++){
            while(j > 0 && needle.charAt(j) != haystack.charAt(i)){
                j = next[j-1];
            }
            if(needle.charAt(j) == haystack.charAt(i)) j++;
            // 如果模式串到结尾了,表示能完全匹配,返回开始索引
            if(j == nn){
                return i - nn + 1;
            } 
        }
        return -1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值