代码随想录第九天|KMP算法

文章介绍了如何使用KMP算法解决两个问题:检测字符串是否有重复的子字符串以及找出字符串中第一个匹配项的下标。KMP算法在处理字符串匹配时,能有效避免不必要的比较。代码示例展示了GetNext函数的实现和算法的应用。
摘要由CSDN通过智能技术生成

459、重复的子字符串

总结:被KMP的折磨的一天,还是不能很好的理解KMP算法,慢慢来慢慢接触

代码:

class Solution {
public:
    void GetNext(int* next,string s)
    {
        int j = 0;
        next[0] = 0;
        for(int i = 1;i < s.size();i++)
        {
            while( j > 0 && s[i] != s[j])
            {
                j = next[j - 1];
            }
            if(s[i] == s[j])
            j++;

            next[i] = j;
        }
    }
    bool repeatedSubstringPattern(string s) {
         if (s.size() == 0) {
            return false;
        }
        int next[s.size()];
        GetNext(next, s);
        int len = s.size();
        if (next[len - 1] != 0 && len % (len - (next[len - 1] )) == 0) {
            return true;
        }
        return false;
    }
};

28、找出字符串中第一个匹配项的下标

代码:

class Solution {
public:
    void GetNext(int* next,string needle)
    {
        int j = 0;
        next[0] = 0;
        for(int i = 1;i < needle.size();i++)
        {
            while(j > 0 && needle[i] != needle[j])
            {
                j = next[j - 1];
            }
            if(needle[i] == needle[j])
            {
                j++;
            }
            next[i] = j;
        }
    }
    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 - needle.size() + 1);
        }
        return -1;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值