Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Repeated Substring #113

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions 0459-Repeated-Substring-Pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'''
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.)
'''
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
i, j, l = 1, 0, len(s)
lookup = [0] * (l + 1)

while i < l:
if s[i] == s[j]:
i += 1
j += 1
lookup[i] = j
elif not j:
i += 1
else:
j = lookup[j]
return lookup[l] and not lookup[l] % (l - lookup[l])