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.)

Solution:

My p[i] stands for longest common string length of prefix string and the string ended with position i.


The important point is the last one: len % (len - p[len - 1]) == 0


for a string like below, if p[len-1] = 15, len=20:


#####~~~~~^^^^^$$$$$
#####~~~~~^^^^^$$$$$


by p[len-1] = 15, we know the strings colored red are the same.


so you can infer that:


##### == ~~~~~


~~~~~ == ^^^^^


^^^^^ == $$$$$


The whole is repeating as #####


the length of it is 5, which can be completely divided by len.


That's how this final condition works.

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int[] table = new int[s.length()];
        int prefixLength = 0;
        for (int currentIndex = 1; currentIndex < s.length(); currentIndex ++) {
            while (prefixLength > 0 && s.charAt(prefixLength) != s.charAt(currentIndex)) {
                prefixLength = table[prefixLength - 1];
            }
            if (s.charAt(prefixLength) == s.charAt(currentIndex)) {
                prefixLength++;
            }
            table[currentIndex] = prefixLength;
        }
        System.out.println((Arrays.toString(table)));
        int len = s.length();
        return table[len - 1] > 0 && (len % (len - table[len - 1]) == 0);
    }
}