LeetCode 第28题 实现strStr() - KMP算法实现

@[TOC](LeetCode 第28题 实现strStr() 做题记录)

题目描述

在这里插入图片描述

我的解法

思路

最直接的方法——暴力求解
两层循环,时间复杂度O(mn) m和n分别是两个字符串的长度
上面超出时间限制了,那就不得不用KMP算法了

对应Java代码

执行时超出了时间限制


class Solution {
    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0) {
            return 0;
        }
        int hj,ni;
        for(int hi = 0; hi < haystack.length(); hi ++){
            hj = hi;
            ni = 0;
            while(haystack.charAt(hj) == needle.charAt(ni)){
                if(ni == needle.length() - 1){
                    return hi;
                }
                if(hj == haystack.length() - 1){
                    break;
                }
                hj++;
                ni++;
            }
        }
        return -1;
    }
}

更优解法

此部分转载于公众号代码随想录

思路

KMP算法

对应Java代码

在这里插入图片描述

class Solution {
    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0){ return 0; }
        int nLen = needle.length();
        int hLen = haystack.length();
        int[] next = new int[nLen];
        getNext(next, needle);
        int j = -1;
        for(int i = 0; i < hLen; i++){
            while( j >= 0 && haystack.charAt(i) != needle.charAt(j + 1)){
                j = next[j];
            }
            if(haystack.charAt(i) == needle.charAt(j + 1)){
                j++;
            }
            if(j == nLen - 1){
                return i - nLen + 1;
            }
        }
        
        return -1;
    }  
    public void getNext(int[] next, String needle){
        int j = -1; //定义前缀
        next[0] = j;
        for(int i = 1; i < next.length; i++){
            while(j >= 0 && needle.charAt(i) != needle.charAt(j + 1)){
                j = next[j];
            }
            if(needle.charAt(i) == needle.charAt(j + 1)){
                j++;
            }
            next[i] = j;
        }
    }
}

复杂度分析

时间复杂度:O(m + n) m和n分别是文本串和模式串的长度
空间复杂度:O(n) 用来存储模式串的next数组

收获总结

KMP算法的原理和实践写法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值