这道题我的方法太暴力,人家解得巧妙不已,我的方法如下:
public class Solution {
public boolean repeatedSubstringPattern(String str) {
int length = str.length() / 2 +1;
for(int i = 1;i<length;i++){
String sub = str.substring(0,i);
if(check(str.substring(i),sub))
return true;
}
return false;
}
private boolean check(String str,String sub){
int strLen = str.length(),subLen = sub.length();
int checkNum = strLen % subLen;
if(checkNum != 0){
return false;
}
int i = 0;
while(i <= strLen - subLen){
String checkStr = str.substring(i,i+subLen);
if(checkStr.equals(sub))
i +=subLen;
else
return false;
}
return true;
}
}
讨论中高票答案:
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;
}
2016/12/15