原题网址:https://leetcode.com/problems/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 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.)
方法:只需要检查切分为素数个。
public class Solution {
public boolean repeatedSubstringPattern(String str) {
char[] sa = str.toCharArray();
boolean[] checked = new boolean[sa.length + 1];
for(int i = 2; i <= sa.length; i++) {
if (sa.length % i != 0) continue;
if (checked[i]) continue;
for(int j = i; j <= sa.length; j += i) {
checked[j] = true;
}
boolean succ = true;
ALL: for(int j = 0; j < i - 1; j++) {
for(int k = 0; k < sa.length / i; k++) {
if (sa[j * sa.length / i + k] != sa[(j + 1) * sa.length / i + k]) {
succ = false;
break ALL;
}
}
}
if (succ) return true;
}
return false;
}
}