力扣刷题笔记(十一)KMP算法

该文章介绍了如何使用C++实现KMP算法,用于在字符串haystack中查找子串needle。getNext函数计算了needle的next数组,用于动态规划过程。在strStr函数中,利用next数组进行匹配,避免不必要的回溯,提高了查找效率。
摘要由CSDN通过智能技术生成

对应题目:力扣28题

class Solution {
public:
//kmp算法
    void getNext(int* next, const string& s) {
          //前缀结尾
          int frontLast=0;
          //后缀结尾
          int backLast=1;
          next[0]=0;
          for(backLast;backLast<s.size();backLast++){
              while(frontLast>0&&s[backLast]!=s[frontLast])//动态规划持续回溯
                frontLast=next[frontLast-1];//找到backLast-1的最大公共前后缀
              if(s[backLast]==s[frontLast])//包含本身元素,最长公共前后缀长度加1
                frontLast++;
              next[backLast]=frontLast;
          }
    }
    int strStr(string haystack, string needle) {
        if(needle.size()==0)
            return 0;
        int next[needle.size()];
        getNext(next,needle);
        int j=0;
        for(int i=0;i<haystack.size();i++){
            while(j>0&&haystack[i]!=needle[j]){//持续回溯直到找到相等的元素
                 j = next[j - 1];
            }
            if(haystack[i]==needle[j])
                j++;
            if(j==needle.size())
                return i-j+1;
        }
        return -1;
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值