LeetCode 28 实现strStr() 字符串匹配KMP

本文深入探讨了KMP算法的原理与应用,通过对比N*M算法,详细讲解了KMP算法如何避免重复匹配,提高字符串搜索效率。文章提供了完整的KMP算法实现代码,并解析了其核心函数getFail的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// N*M算法
// KMP算法,这里是学习刘汝佳大神书上的代码



class Solution {
    // public int strStr(String haystack, String needle){
    //     if (needle == null || needle.length() == 0)    return 0;
    //     if (haystack == null || haystack.length() == 0) return -1;
    //     if (haystack.length() < needle.length()) return -1;
    //     boolean flag = false;
    //     for (int i = 0;i < haystack.length() - needle.length() + 1; i++){
    //         flag = false;

    //         for (int j = 0, index = i; j < needle.length(); j++,index++){
    //             if (haystack.charAt(index) != needle.charAt(j)){
    //                 flag = true;
    //             }
    //         }
    //         if (!flag)
    //             return i;
    //     }
    //     return -1;
    // }

    public int strStr(String haystack, String needle){
        if (needle == null || needle.length() == 0)    return 0;
        if (haystack == null || haystack.length() == 0) return -1;
        if (haystack.length() < needle.length()) return -1;
        int[] f = new int[needle.length() + 1];
        getFail(needle, f);

        int n = haystack.length();
        int m = needle.length();
        int j = 0;
        for (int i = 0;i < n;i ++){
            while(j != 0 && haystack.charAt(i) != needle.charAt(j))
                j = f[j];
            
            if (haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == m) return i - m + 1;
        }
        return -1;
    }

    public void getFail(String P, int[] f){
        int m = P.length();
        f[0] = 0;
        f[1] = 0;
        for (int i = 1; i < m; i++){
            int j = f[i];
            while (j != 0 && P.charAt(i) != P.charAt(j))
                j = f[j];
            f[i + 1] = P.charAt(i) == P.charAt(j) ? j + 1 : 0;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值