Day09代码随想录算法训练营第一天 |28. 找出字符串中第一个匹配项的下标, 459.重复的子字符串

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

题目链接: 28. 找出字符串中第一个匹配项的下标
思路: 本题就是KMP的裸题,利用KMP进行匹配,(我习惯next数组从1开始),如果初学者一定要将

  1. 暴力求解的思路
  2. KMP的匹配思路
  3. next数组的更新思路

都自己画图模拟思考,推导一遍,以便加深理解。
我自己用文字很难表述,所以直接为大家献上视频。
4. 帮你把KMP算法学个通透!(理论篇)
5. 帮你把KMP算法学个通透!(求next数组代码篇)

为大家献上我的代码(自己的习惯性写法):

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = needle.size();
        vector<int> next(m + 1);
        haystack = ' ' + haystack, needle = ' ' + needle;
        for(int i = 2, j = 0; i < needle.size(); i++){//求next数组
            while(j && needle[i] != needle[j + 1]) j = next[j];
            if(needle[i] == needle[j + 1]) j++;
            next[i] = j;
        }

        for(int i = 1, j = 0; i < haystack.size(); i++){//KMP匹配过程
            while(j && haystack[i] != needle[j + 1]) j = next[j];
            if(haystack[i] == needle[j + 1]) j++;
            if(j == m) return i - needle.size() + 1;
        }
        return -1;
    }
};

459.重复的子字符串

结论: 求最小周期是KMP的经典应用之一(一定记住)。n - next[n]就是该串的最小周期(前提是该串是重复性的串)。
思路: 直接上视频吧,文字描述太烦了(狗头)
解答链接: LeetCode:459.重复的子字符串

代码1: (在字符匹配环节可以直接调用库函数find(),我是自己写的KMP匹配)

class Solution {
public:
    bool repeatedSubstringPattern(string s) { 
        string temp = s;
        string ss = s + s;
        ss.erase(ss.begin()); ss.erase(ss.end() - 1);
        if(ss == temp) return true;

        int n = temp.size();
        vector<int> next(n + 1);
        temp = ' ' + temp;
        for(int i = 2, j = 0; i <= n; i++){
            while(j && temp[i] != temp[j + 1]) j = next[j];
            if(temp[i] == temp[j + 1]) j++;
            next[i] = j;
        }
        for(int i = 1, j = 0; i <= ss.size(); i++){
            while(j && ss[i] != temp[j + 1]) j = next[j];
            if(ss[i] == temp[j + 1]) j++;
            if(j == n) return true;
        }
        return false; 
    }
};

代码2:

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int n = s.size();
        s = ' ' + s;
        vector<int> next(n + 1);
        for(int i = 2, j = 0; i <= n; i++){
            while(j && s[i] != s[j + 1]) j = next[j];
            if(s[i] == s[j + 1]) j++;
            next[i] = j;
        }
        int t = n - next[n];
        return t < n && n % t == 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值