Description
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
Constraints:
1 <= s.length <= 10^4
s consists of lowercase English letters.
Solution
Iteration
Search from the left, when current sub-string has the same elements as the whole string, we start to check if the length of the sub-string could be divided by the whole string without residuals. Keep checking until the result is no longer great than 1.
Time complexity:
o
(
s
.
l
e
n
g
t
h
)
o(s.length)
o(s.length)
Space complexity:
o
(
s
.
l
e
n
g
t
h
)
o(s.length)
o(s.length)
Math
If a string is periodical, then it must exist in s+s[1:-1]
Code
Iteration
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
uniq_chs = set(s)
sub_string = ''
for i in range(len(s)):
sub_string += s[i]
if not(uniq_chs - set(sub_string)):
times = len(s) // len(sub_string)
residuals = len(s) % len(sub_string)
if times <= 1:
return False
if residuals == 0 and s == sub_string * times:
return True
return False
Math
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return s in (s + s)[1:-1]