不会真看不懂吧!KMP字符匹配算法(leetcode #28)

在这里插入图片描述
在这里插入图片描述

参考:
【soso字幕】汪都能听懂的KMP字符串匹配算法【双语字幕】

KMP,Sunday等高级算法在处理长文本时候有优势,在字符串较短时候因为需要预处理和额外空间,效率反而没有BF算法高

比如leetcode #28,滑动窗口居然比kmp快得多:

kmp实现:

 class Solution {
        public int strStr(String haystack, String needle) {
            if (needle.equals("")) return 0;
            if (haystack.equals("")) return -1;
            char[] hstr = haystack.toCharArray();
            char[] nstr = needle.toCharArray();
            int [] next = getnext(nstr);
            //匹配
            int m = 0, n = 0;
            while (m < hstr.length && n < nstr.length) {
                if (hstr[m] == nstr[n]) {
                    //单次匹配成功
                    m++;
                    n++;
                } else if (hstr[m] != nstr[n] && n > 0) {
                    //单次匹配失败但n不为0
                    n = next[n - 1];
                    continue;
                } else if (hstr[m] != nstr[n] && n == 0) {
                    //单次匹配失败且n=0
                    m++;
                }
            }

            return  n == nstr.length? m - n: -1;
        }

        public int[] getnext(char[] str){
                //构建next数组
                int []next = new int[str.length];
                int i = 1;
                int j = 0;
                next[0] = 0;
                while (i < str.length) {
                    if (str[i] == str[j]) {
                        //i与j相同时
                        next[i] = j + 1;
                        i++;
                        j++;
                    } else {
                        //i与j不同时,以j是否为0判断j是否移动
                        if (j == 0) {
                            next[i] = j;
                            i++;
                        }
                        if (j != 0) {
                            j = next[j - 1];
                            //再比较j与i
                            continue;
                        }
                    }
                }
                return next;
            }

        }

滑动窗口实现:

class Solution {
  public int strStr(String haystack, String needle) {
    int L = needle.length(), n = haystack.length();

    for (int start = 0; start < n - L + 1; ++start) {
      if (haystack.substring(start, start + L).equals(needle)) {
        return start;
      }
    }
    return -1;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值