day09力扣28找出字符串中第一个匹配的下标_459重复的字符串

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

简单的模式匹配:主串指针回溯,时间复杂度O(mn)
KMP算法:主串指针不回溯,时间复杂度O(m+n)
  • KMP的代码:双指针,主串指针和模式串指针,主串指针不回溯,模式串指针指向下一个字符或者指向next数组的值;
  • next数组:双指针,一个指向next数组的下标从0开始递增,一个指向插入这个位置的值。
class Solution {
public:

    int strStr(string haystack, string needle) {
        if(needle.size() == 0) return 0;
        int nextLength = needle.size();
        vector<int> next(nextLength);
        //处理next数组,需要考虑next数组长度等于0,1,大于1
        if(needle.size() == 1) next[0] = -1;
        else{
        next[0]= -1, next[1] = 0;
        int pos = 0;
        for(int npos = 2; npos < nextLength; npos++){//i指向字符串next的每一位,pos给next[i]赋值
            pos = next[npos - 1];
            while(pos != 0 && needle[npos-1]!=needle[pos]) pos = next[pos];
            //cout << npos << endl; 
            if(needle[npos-1] == needle[pos]){ next[npos]=pos+1; }
            else next[npos]=0;
        }
        }
		int i = 0,j = 0;
        //i指向主串,j指向模式串        
        while(i < haystack.size()){
            if((j == -1) || (haystack[i] == needle[j])) {
                i++, j++;
                if(j == needle.size()) return (i-j);
            }
            else{
                j = next[j];
            }   
        }
        return -1;
    }
};

459重复的字符串

采用确定一个子字符串,再主串中判断是否是主串的字符串,不是继续找下一个,直到找到主串的一半,如果还是不是,则返回false。
时间复杂度O(n^2)
空间复杂度O(1)

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        bool str = true;
        int length = s.size();
        if(length <= 1) return false; 
        for(int i = 0; i * 2 < length; i++){
            if(length % (i+1) == 0){
                str = true;
                for(int j = i+1; j < s.size(); j++){
                    if(s[j] != s[j-i -1]){
                        str = false;break;
                    }
                }
                if(str) return true;
            }
        }
        return false;
    }
};
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值