[leetcode] problem 459 – repeated substring pattern

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

No.1

Input: “abab”

Output: True

Explanation: It’s the substring “ab” twice.

No.2

Input: “aba”

Output: False

No.3

Input: “abcabcabcabc”

Output: True

Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean (String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(s);

for (int i = n / 2; i >= 1; i--) {
if (n % i == 0) {
String str = sb.substring(0, i);
int j = 1;

for (; j < n / i; j++) {
if (!str.equals(sb.substring(j * i, j * i + i)))
break;
}

if (j == n / i)
return true;
}
}

return false;
}