代码随想录算法训练营Day9 Leetcode28(KMP算法)、459

本文介绍了如何使用C++实现LeetCode中的两个问题:在字符串`haystack`中查找子串`needle`的第一个匹配位置,以及判断给定字符串`s`是否能通过重复某个子串组成。涉及到了next数组和子串遍历的算法原理。
摘要由CSDN通过智能技术生成

1.Leetcode28

问题描述:

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回  -1 

代码解析:
int strStr(string haystack, string needle) {
    // 获取模式串的next数组
    int* next = getNext(needle);

    //j代表已经匹配到模式串中的哪个下标
    int j = -1;

    
    for (int i = 0; haystack[i]; i++) {
        while (j != -1 && haystack[i] != needle[j + 1])j = next[j];
        if (haystack[i] == needle[j + 1])j += 1;
        if (needle[j + 1] == '\0')return i - needle.size() + 1;
    }
    return -1;
}

int* getNext(string t) {
    int tlen = t.size();
    int* next = new int[tlen];
    next[0] = -1;
    int j = -1;
    for (int i = 1; i < tlen; i++) {
        while (j != -1 && t[i] != t[j + 1])j = next[j];
        if (t[i] == t[j + 1])j += 1;
        next[i] = j;
    }
    return next;
}

2.Leetcode459

问题描述:

给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。

代码解析:
 bool repeatedSubstringPattern(string s) {
        int n=s.size();
        //至少存在两个相同的字串,因此枚举到长度为一半的子串截止
        for(int i=1;i*2<=n;i++){
            //长度为母串长度的倍数才能满足条件
            if(n%i==0){
                bool k=true;
                for(int j=i;j<n;j++){
                    if(s[j]!=s[j-i]){
                        k=false;break;
                    }
                }
                if(k)return true;

            }
        }
        return false;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值