一开始写的总是超时,最后是看了提示才写出来的。关键是重复字符串长度一定不大于s的二分之一,而且s的长度一定能整除字符串长度。满足这个条件的重复字符串就大大减少了,就不会超时了。下面是我写的:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
for(int i = n/2; i > 0; --i)
{
if(n % i == 0)
{
string sub = s.substr(0, i);
string res = "";
for(int j = 0; j < n / i; ++j)
{
res += sub;
}
if(res == s)
return true;
}
}
return false;
}
};
更好的方法是KMP:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int len = s.length();
int next[len+1];
next[0] = -1;
int j = 0, k = -1;
while( j < len )
{
if( k==-1 || s[j]==s[k] )
next[++j] = ++k;
else k = next[k];
}
return next[len] && next[len]%(len-next[len])==0;
}
};