Version #3 九章答案TODO
Version #2 KMP之类的?懒得想了实在
Version #1 无脑分割然后append然后与原string比较
10.35 %
public class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s == null || s.length() <= 1) return false;
int length = s.length();
// 0, 1, 2, 3 length = 4
//sub = 0, 1 s.subString(0, length / 2)
// 0, 1, 2 length = 3
//sub = 0, 1 s.subString(0, length / 2) ... we don't care
for (int end = 1; end <= length / 2; end++) {
String sub = s.substring(0, end);
if (isRepeated(s, sub)) return true;
}
return false;
}
private boolean isRepeated(String s, String sub) {
int shortLength = sub.length();
int longLength = s.length();
if (longLength % shortLength != 0) return false;
int multi = longLength / shortLength;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < multi; i++) {
sb.append(sub);
}
//System.out.println(sb.toString());
return sb.toString().equals(s);
}
}
No comments:
Post a Comment