459.Repeated-Substring-Pattern
459. Repeated Substring Pattern
题目地址
https://leetcode.com/problems/repeated-substring-pattern/
题目描述
代码
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.
Approach #2 Concatenation
Repeated pattern string looks like PatternPattern
, and the others like Pattern1Pattern2
.
Let's double the input string:
Now let's cut the first and the last characters in the doubled string:
It's quite evident that if the new string contains the input string, the input string is a repeated pattern string.
Last updated