Given a non-empty string checkif it can be constructed by taking a substring of it and appending multiplecopies of the substring together. You may assume the given string consists oflowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's thesubstring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input:"abcabcabcabc"
Output: True
Explanation: It's thesubstring "abc" four times. (And the substring "abcabc"twice.)
翻译:给定一个非空字符串检查,如果它可以通过取其子字符串并将子字符串的多个副本附加在一起构造。您可以假定给定字符串仅由小写英文字母组成,其长度不超过10000。
分析:直接假设他重复的次数,然后将它的子串和原串比较,若找到一个重复的次数,则返回ture.可能时间复杂度比较高,代码如下:
public class Solution {
public boolean test(String s,int length){
//比较他们的是否是重复的
int count=s.length()/length;
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=s.charAt(i%count)) return false;//直接到了固定的数,循环回来比较
}
return true;
}
public booleanrepeatedSubstringPattern(String s) {
int len=s.length();
if(len==1) return false;
//假设字符串循环2到len次
boolean flag=false;
for(int i=2;i<=len&&!flag;i++){
if(len%i!=0) continue;
flag=test(s,i);
}
return flag;
}
}