KMP算法
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int len = s.size();
vector<int> next(len);
next[0] = -1;
int k = -1;//前缀
int j = 0;
while(j < len){
if(k == -1 or s[j] == s[k]){
k++;
j++;
next[j] = k;
}
else{
k = next[k];
}
}
if(s[j] == s[k] and len%(j-k) == 0) return true;
return false;
}
};
构造s+s
假设给定字符串 可由一个子串 重复 次构成,即 。现构造新字符串 ,由于 ,则 。去掉t的开头与结尾两位,则这两处的子串被破坏掉,此时 中包含 个子串。由于 中包含 个子串, 中包含 个子串,若 中包含 ,则有 ,可得 ,由此我们可知字符串 可由一个子串 重复至少2次构成,判定为true;反之,若 中不包含 ,则有 ,可得 , 只能为1,由此我们可知字符串 ,假定的子串就为 s本身,判定为false。来源于题解
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string str=s+s;
str=str.substr(1,str.size()-2);
if(str.find(s)==-1)
return false;
return true;
}
};