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

文章介绍了如何使用KMP算法解决LeetCode上的两道题目,分别是找出字符串中第一个匹配项的下标和检查是否存在重复的子字符串。通过暴力法和KMP算法的对比,展示了KMP算法在处理字符串匹配问题时的效率优势。
摘要由CSDN通过智能技术生成

LeetCode28. 找出字符串中第一个匹配项的下标(KMP)

题目链接
视频讲解

自己实现

// 暴力法
class Solution {
public:
    int strStr(string haystack, string needle) {
        bool flag = false;
        int i = 0, j = 0;
        for(int i = 0; i < haystack.size(); i++) {
            int j = 0;
            for(; j < needle.size(); j++) {
                if(haystack[i + j] != needle[j]) break;
            }
            if(j == needle.size()) return i;
        }
        return -1;
    }
};

题解

// KMP
class Solution {
public:
    int strStr(string haystack, string needle) {
        vector<int> next = getNext(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;
    }

    vector<int> getNext(string needle) {
        // 1. 初始化
        // i 表示后缀最后一位,j 表示前缀最后一位
        vector<int> next(needle.size(), 0);
        int j = 0;
        // i 从 1 开始 才能进行比较 aabaabaaf 从aa开始
        for(int i = 1; i <  needle.size(); i++) {
            // 前后缀最后一个字母不相同 注意这里是while,查找前一个位置
            while(j > 0 && needle[i] != needle[j]) j = next[j - 1];
            // 先后缀最后一个字母相同
            if(needle[i] == needle[j]) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
};

总结

LeetCode459. 重复的子字符串

题目链接
视频讲解

题解

// 移动匹配
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        string t = s + s;

        t.erase(t.begin());
        t.erase(t.end() - 1);

        if(t.find(s) == -1) return false;
        return true;
    }
};

// KMP
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        
        vector<int> next = getnext(s);

        int len = s.size();
        // 如果可以被整除则为true 去掉最后一个为0的情况
        if(next[len - 1] != 0 && len % (len - next[len - 1]) == 0) return true;
        return false;
    }

    vector<int> getnext(string s) {
        // 1.初始化
        vector<int> next(s.size(), 0);
        // j 代表前缀,i代表后缀
        int j = 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;
        }
        return next;

    }
};

总结

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值