給一個(gè)字符串,判斷這個(gè)字符串能不能被某一個(gè)子串完全重復(fù)分割。
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
Input: "aba"
Output: False
分析:
能夠被某一個(gè)子串重復(fù)分割,就意味著這個(gè)子串的長度能夠整除總的字符串的長度
string.length % substring.length = 0
最長的子串可能滿足這個(gè)要求的,長度也只可能為 string.length / 2
思路:
先從index = 1開始截取子串
然后用一個(gè)指針往后遍歷當(dāng)前長度的子串,看是否跟原子串相同
如果遍歷到最后都是相同的,就返回true
如果整個(gè)字符串都截取完了都沒結(jié)果,就返回false
代碼:
public boolean repeatedSubstringPattern(String str) {
if (str == null || str.length() == 0 || str.length() == 1) {
return false;
}
// end index for every substring
int endIndex = 1;
// length of subStr cannot exceed half of str's length
while (endIndex <= str.length() / 2) {
if (str.length() % endIndex == 0) {
String subStr = str.substring(0, endIndex);
// total times we should traverse
int loopAmount = str.length() / endIndex;
int i = 1;
for (i = 1; i < loopAmount; i++) {
if (!subStr.equals(str.substring(endIndex * i, endIndex + endIndex * i))) {
break;
}
}
// if reaches the end of string, return true
if (i == loopAmount) {
return true;
}
}
endIndex++;
}
return false;
}