LeetCode #459 - Repeated Substring Pattern

题目描述:

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"
Output: False

Example 3:

Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int n=s.size();
        for(int i=1;i<=n/2;i++)
        {
            if(n%i==0)
            {
                string x;
                while(x.size()<s.size()) x+=s.substr(0,i);
                if(x==s) return true;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/81255628
今日推荐