【leetcode】459. Repeated Substring Pattern

problem

459. Repeated Substring Pattern

solution1:

这道题给了我们一个字符串,问其是否能拆成n个重复的子串。那么既然能拆分成多个子串,那么每个子串的长度肯定不能大于原字符串长度的一半,那么我们可以从原字符串长度的一半遍历到1,如果当前长度能被总长度整除,说明可以分成若干个子字符串,我们将这些子字符串拼接起来看跟原字符串是否相等。 如果拆完了都不相等,返回false。

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int n = s.size();
        for(int i=n/2; i>0; i--)
        {
            if(n%i==0)
            {
                string t = "";
                int cnt = n / i;
                for(int j=0; j<cnt; j++)
                {
                    t += s.substr(0, i);
                }
                if(t==s) return true;
            }
        }
        return false;  
    }
};

solution2:

参考

1. Leetcode_459. Repeated Substring Pattern;

2. GrandYang;

3. 从头到尾彻底理解KMP;

原文地址:https://www.cnblogs.com/happyamyhope/p/10529349.html