Saturday, July 8, 2017

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 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:

If string s satisfies the condition, the maximum valid substring it can split is s = x + x.

In this case, s + s = x + x + x + x.

We can see the second substring and the first substring forms a new string s.

 Therefore, we break the first and last x of s + s, and if we can still find an s, this string is a valid string.

Now consider s = x + x + x.

s + s = x + x + x + x + x + x.

We break the first and last x and the string becomes x' + x + x + x + x + x''.

We can see the remaining substring still contains s.

Therefore, in general, we duplicate s to s + s and remove the first and last character.

If we can still find an s in this substring, s is valid.



Code:


public class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String str = (s + s).substring(1, s.length() + s.length() - 1);
        return str.indexOf(s) != -1;
    }
}