Description
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
Example 3:
Input: "abcabcabcabc"Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
Solution
Basic
Brute-force with optimisation
public class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s == null || s.length() < 2) {
return false;
}
int len = s.length();
boolean isValid = true;
for (int subLen = 1; subLen <= len / 2; ++subLen) {
if (len % subLen != 0) continue; // do some math to filter obvious invalid subLen
isValid = true; // a flag use to break nested loop
for (int i = subLen; isValid && i <= len - subLen; i += subLen) {
for (int j = 0; isValid && j < subLen; ++j) {
if (s.charAt(j) != s.charAt(i + j)) isValid = false;
}
}
if (isValid) return true;
}
return false;
}
}
TODO: Optimisation
KMP