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
思路:这题巧妙的地方在于剪枝,n % j == 0的时候,才判断,而且生成也是n / j个substr;
class Solution {
public boolean repeatedSubstringPattern(String s) {
if(s == null || s.length() == 0) {
return false;
}
int n = s.length();
for(int j = 1; j < s.length(); j++) {
// 巧妙的地方在于剪枝,n % j == 0,也就是整数取余==0的时候才判断;
if(n % j == 0) {
int m = n / j;
String substr = s.substring(0, j);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < m; i++) {
sb.append(substr);
}
if(sb.toString().equals(s)) {
return true;
}
}
}
return false;
}
}