一:题目
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.)
二:解体分析
思路一:笨方法,时间复杂度O(n2),截取前1,2,...,s.length()/2-1,长度,查看拼接后的字符串是否与源字符串相同
思路二:KMP算法,时间复杂度O(n) 详细介绍可参考博客 从头到尾彻底理解KMP
三:代码实现
方法一:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
//符合条件,则子串至少要重复两次,即子串最大长度是从开始位置到字符串的中间位置
int i=0;
int j;
string substring;
string multipleString;
for(i=0;i<s.length()/2;i++){
//分别获得前1,2,3,...,s.length()/2-1的子串
substring=s.substr(0,i+1); //第一个参数,截取字符串的开始位置,第二个参数,截取的长度
multipleString="";
if(s.length()%substring.length()==0){
for(j=1;j<=s.length()/substring.length();j++)
multipleString+=substring;
if(s==multipleString)
return true;
}
}
return false;
}
};
方法二(详见博客 点击打开链接)
class Solution {
public:
bool repeatedSubstringPattern(string s) {
//KMP算法
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;
}
};