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.)
Subscribe to see which companies asked this question.
判断字符串是否是由一个子字符串重复得来。使用暴力的方法,把字符串分别等分成长度为1,2...n/2的子字符串来进行比较。只要分成的每个子字符串都想等,就返回true。
代码:
class Solution
{
public:
bool repeatedSubstringPattern(string s)
{
int n = s.size(), i, j;
for(i = 1; i <= n / 2; ++i)
{
if(n % i != 0) continue;
string tmp = s.substr(0, i);
for(j = i; j < n; j += i)
{
if(s.substr(j, i) != tmp) break;
}
if(j == n) return true;
}
return false;
}
};