给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例 1:
输入: "abab" 输出: True 解释: 可由子字符串 "ab" 重复两次构成。
示例 2:
输入: "aba" 输出: False
示例 3:
输入: "abcabcabcabc" 输出: True 解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)
解法一暴力:
那么既然能拆分成多个子串,那么每个子串的长度肯定不能大于原字符串长度的一半,那么我们可以从原字符串长度的一半遍历到1,如果当前长度能被总长度整除,说明可以分成若干个子字符串,我们将这些子字符串拼接起来看跟原字符串是否相等。 如果都不相等,返回false。
KMP:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int len = s.size();
vector<int> next(len + 1, 0);
next[0] = -1;
int i = 0, j = -1;
while(i < len)
{
if(s[i] == s[j] || j == -1)
{
next[++i] = ++j;
}
else
{
j = next[j];
}
}
return next[len] && (len % (len - next[len]) == 0);
}
};