public boolean repeatedSubstringPattern(String s) {
int n = s.length();
if (n == 1) return false;
// [0, i) [x, n)
for (int i = 1; i <= n/2; i++) {
if (s.charAt(i-1) != s.charAt(n-1)) continue;
if (n % i != 0) continue;
int m = n / i;
if (m < 2) continue;
String tmp = s.substring(0, i);
int j = 1;
for (; j < m; j++) {
if (!s.substring(j * i, j * i + i).equals(tmp))
break;
}
if (j == m) {
return true;
}
}
return false;
}
public List<String> repeatedSubstringPattern(String s) {
List<String> res = new ArrayList<>();
int n = s.length();
for (int i = 1; i <= n/2; i++) {
if (n % i != 0) continue;
if (s.charAt(i-1) != s.charAt(n-1)) continue;
int m = n / i;
if (m < 2) continue;
int j = 1;
for (; j < m; j++) {
int lo = j * i;
int hi = lo + i;
if (!s.substring(0, i).equals(s.substring(lo, hi))) {
break;
}
}
if (j == m) {
res.add(new StringBuilder(s.substring(0, i)).append(m).toString());
}
}
return res;
}
459. Repeated Substring Pattern
最新推荐文章于 2020-08-25 17:49:51 发布