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.)
我的思路是如果序列是以重复的子序列组成的,那么每一个子序列的第一个字母肯定是整个序列的第一个字母。找到整个序列所有这个字母的位置k,那么[0,k-1]就是所有的子序列,一个一个子序列试。算法复杂度是0(n)。
public class Solution {
public boolean repeatedSubstringPattern(String str) {
if (str.length() == 0 || str == null) {
return true;
}
int i = 1, j = 0;
int length = 0;
char[] chars = str.toCharArray();
char startch = chars[0];
boolean findstartch = false;
boolean findsubstr = false;
int flag = 1;
while(i < chars.length) {
if (chars[i] == startch) {
findstartch = true;
if (findsubstr == false && flag == 1) {
length = i;
flag = 0;
}
}
if (findstartch == true) {
if (chars[j] == chars[i]) {
j++;
} else {
j = 0;
i = length;
findsubstr = false;
findstartch = false;
flag = 1;
}
if (j >= length) {
findsubstr = true;
j = 0;
} else {
findsubstr = false;
}
}
i++;
}
return findsubstr;
}
}
public class Solution {
public boolean repeatedSubstringPattern(String str) {
//This is the kmp issue
int[] prefix = kmp(str);
int len = prefix[str.length()-1];
int n = str.length();
return (len > 0 && n%(n-len) == 0);
}
private int[] kmp(String s){
int len = s.length();
int[] res = new int[len];
char[] ch = s.toCharArray();
int i = 0, j = 1;
res[0] = 0;
while(i < ch.length && j < ch.length){
if(ch[j] == ch[i]){
res[j] = i+1;
i++;
j++;
}else{
if(i == 0){
res[j] = 0;
j++;
}else{
i = res[i-1];
}
}
}
return res;
}
}
另一种比较清晰的解法如下:
public boolean repeatedSubstringPattern(String str) {
int l = str.length();
for(int i=l/2;i>=1;i--) {
if(l%i==0) {
int m = l/i;
String subS = str.substring(0,i);
StringBuilder sb = new StringBuilder();
for(int j=0;j<m;j++) {
sb.append(subS);
}
if(sb.toString().equals(str)) return true;
}
}
return false;
}