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.)
bool repeatedSubstringPattern(string s) {
if(s.size()<=1)return false;
int i=0;
int j=1;
vector<int>table(s.size(),0);
while(j<s.size()){
if(s[i]==s[j]){
i++;
table[j]=i;
j++;
}
else{
if(i==0){
j++;
}
else{
i=table[i-1];
}
}
}
return table[s.size() - 1] && table[s.size() - 1] % (s.size() - table[s.size() - 1]) == 0;
}
第二种简单方法:将s拓展为s2=s+s,然后截取s3 = s2(1,s2.size()-1)
如果满足能够由子串重复的条件的话,那么s3中必包含s1
bool repeatedSubstringPattern(string s) {
return (s+s).substr(1,2*s.size()-1).find(s)!=s.size()-1;
}
2019-03-02更新
KMP算法后续:
28. Implement strStr() https://leetcode.com/problems/implement-strstr/
KMP算法的实现:
1.next数组
vector<int> getNext(string s){
vector<int>next(s.size(),0);
next[0]=-1;
int k=-1;
int j=0;
while(j<s.size()-1){
if(k==-1||s[k]==s[j]){
k++;
j++;
next[j]=k;
//上述三行写成next[++j]=++k;也可以,但是速度会慢很多。从99%直接降到了20多%
}else{
k=next[k];
}
}
return next;
}
参考https://blog.youkuaiyun.com/lannister_awalys_pay/article/details/83957640
2.匹配kmp
int kmp(string t,string s){
int i=0;
int j=0;
vector<int>next;
next = getNext2(s);
int _t = t.size();
int _s = s.size();
while(i<_t&&abs(j)<_s){
//abs(j)是因为j可能会取到-1
// //此时p.size和-1比较会出现小于-1,对j取绝对值比较也可以
if(j==-1||t[i]==s[j]){
i++;
j++;
}else{
j=next[j];
}
}
return j==_s?i-j:-1;
}
暴力解法
int force(string t,string s){
for(int i=0;i<=t.size()-s.size();i++){
int j=0;
for(;j<s.size();j++){
if(t[i+j]!=s[j]){
break;
}
}
if(j==s.size()){
return i;
}
}
return -1;
}