Skip to content

Commit 0c0d869

Browse files
authored
Create repeated-substring-pattern.py
1 parent 8b90bd0 commit 0c0d869

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Given a non-empty string check if it can be constructed by taking a substring of it
5+
# and appending multiple copies of the substring together.
6+
# You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
7+
#
8+
# Example 1:
9+
# Input: "abab"
10+
#
11+
# Output: True
12+
#
13+
# Explanation: It's the substring "ab" twice.
14+
# Example 2:
15+
# Input: "aba"
16+
#
17+
# Output: False
18+
# Example 3:
19+
# Input: "abcabcabcabc"
20+
#
21+
# Output: True
22+
#
23+
# Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
24+
25+
# KMP solution.
26+
class Solution(object):
27+
def repeatedSubstringPattern(self, str):
28+
"""
29+
:type str: str
30+
:rtype: bool
31+
"""
32+
def getPrefix(pattern):
33+
prefix = [-1] * len(pattern)
34+
j = -1
35+
for i in xrange(1, len(pattern)):
36+
while j > -1 and pattern[j + 1] != pattern[i]:
37+
j = prefix[j]
38+
if pattern[j + 1] == pattern[i]:
39+
j += 1
40+
prefix[i] = j
41+
return prefix
42+
43+
prefix = getPrefix(str)
44+
return prefix[-1] != -1 and \
45+
(prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0

0 commit comments

Comments
 (0)