【LeetCode】459 重复的子字符串

【LeetCode】459 重复的子字符串

KMP算法

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int len = s.size();
        vector<int> next(len);
        next[0] = -1;
        int k = -1;//前缀
        int j = 0;
        while(j < len){
            if(k == -1 or s[j] == s[k]){
                k++;
                j++;
                next[j] = k;
            }
            else{
                k = next[k];
            }
        }
        if(s[j] == s[k] and len%(j-k) == 0) return true;
        return false;
    }
};

在这里插入图片描述

构造s+s

假设给定字符串 s s 可由一个子串 x x 重复 n n 次构成,即 s = n x s=nx 。现构造新字符串 t = s + s t=s+s ,由于 s = n x s=nx ,则 t = 2 n x t=2nx 。去掉t的开头与结尾两位,则这两处的子串被破坏掉,此时 t t 中包含 2 n 2 2n-2 个子串。由于 t t 中包含 2 n 2 2n-2 个子串, s s 中包含 n n 个子串,若 t t 中包含 s s ,则有 2 n 2 > = n 2n-2>=n ,可得 n > = 2 n>=2 ,由此我们可知字符串 s s 可由一个子串 x x 重复至少2次构成,判定为true;反之,若 t t 中不包含 s s ,则有 2 n 2 < n 2n-2<n ,可得 n < 2 n<2 n n 只能为1,由此我们可知字符串 s = x s=x ,假定的子串就为 s s s本身,判定为false。来源于题解

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        string str=s+s;
        str=str.substr(1,str.size()-2);
        if(str.find(s)==-1)
            return false;
        return true;
    }
};

在这里插入图片描述

发布了86 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36530992/article/details/103638572
今日推荐