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.)
代码
Approach #1 Regex
Time: O(N^2) && Space: O(1)
because we use greedy regex pattern. Once we have a +, the pattern is greedy.
The difference between the greedy and the non-greedy match is the following:
the non-greedy match will try to match as few repetitions of the quantified pattern as possible.
the greedy match will try to match as many repetitions as possible.
The worst-case situation here is to check all possible pattern lengths from N to 1 that would result in O(N^2) time complexity.
import java.util.regex.Pattern;
class Solution {
public boolean repeatedSubstringPattern(String s) {
Pattern pat = Pattern.compile("^(.+)\\1+$")
}
}
Approach #2 Concatenation
Repeated pattern string looks like PatternPattern, and the others like Pattern1Pattern2.