leetcode 459. 重复的子字符串(Repeated Substring Pattern)

题目描述:

给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。

示例 1:

输入: 
    "abab"
输出: 
    True

解释: 
    可由子字符串 "ab" 重复两次构成。

示例 2:

输入: 
    "aba"
输出: 
    False

示例 3:

输入: 
    "abcabcabcabc"
输出: 
    True

解释: 
    可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)

解法:

class Solution {
public:
    vector<int> getFactor(int num){
        vector<int> res;
        res.push_back(1);
        for(int i = 2; i <= num/2; i++){
            if(num%i == 0){
                res.push_back(i);
            }
        }
        return res;
    }
    
    bool canRepeat(const string& s, int sz, int c){
        if(sz%c != 0){
            return false;
        }
        string pre = s.substr(0, c);
        for(int i = c; i < sz; i += c){
            if(pre != s.substr(i, c)){
                return false;
            }
        }
        return true;
    }
    
    bool repeatedSubstringPattern(string s) {
        int sz = s.size();
        if(sz <= 1){
            return false;
        }
        vector<int> lst = getFactor(sz);
        for(int c : lst){
            if(canRepeat(s, sz, c)){
                return true;
            }
        }
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10593301.html