https://leetcode.com/problems/repeated-substring-pattern/
- String
- KMP
Use KMP failure function. If string is composed of repeated substring, lps[n-1] will be > n/2.
O(n)
O(n)
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
int[] lps = new int[n];
for (int i = 1; i < n; i++) {
int j = lps[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1];
if (s.charAt(i) == s.charAt(j)) j++;
lps[i] = j;
}
return lps[n - 1] > 0 && n % (n - lps[n - 1]) == 0;
}
}