Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You need to determine if s
can be constructed using any substring with more than one character.
s
?
s
contain any characters other than lowercase English letters?
s
consists only of lowercase English letters.Observation: If a string s
can be formed by repeating a substring p
, then concatenating s
with itself (i.e., s + s
) and removing the first and last characters must contain the original string s
in some position other than the start.
ss
by concatenating s
with itself.ss
.s
exists in the modified ss
.s
exists in the modified ss
, then s
can be constructed by repeating a substring.True
if s
is found in modified ss
.False
.ss
and modifying it is O(n), where n is the length of the input string s
.s
is a substring of the modified ss
is also O(n) using Python’s in
operator.def repeatedSubstringPattern(s: str) -> bool:
# Concatenate the string with itself
ss = (s + s)[1:-1]
# Check if the original string s is inside the modified ss
return s in ss
# Example Usage
print(repeatedSubstringPattern("abab")) # Output: True
print(repeatedSubstringPattern("aba")) # Output: False
print(repeatedSubstringPattern("abcabcabc")) # Output: True
print(repeatedSubstringPattern("abcab")) # Output: False
The above code provides a straightforward and efficient method to determine if a string can be constructed by repeating a substring, leveraging string manipulation and pattern recognition techniques.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?