-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathfind-the-shortest-superstring-ii.py
More file actions
37 lines (34 loc) · 1.09 KB
/
find-the-shortest-superstring-ii.py
File metadata and controls
37 lines (34 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Time: O(n + m)
# Space: O(n + m)
# kmp algorithm
class Solution(object):
def shortestSuperstring(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j+1 > 0 and pattern[j+1] != pattern[i]:
j = prefix[j]
if pattern[j+1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
def KMP(text, pattern):
prefix = getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j+1 > 0 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
if j+1 == len(pattern):
break
return text+pattern[j+1:] # modified
result1 = KMP(s1, s2)
result2 = KMP(s2, s1)
return result1 if len(result1) < len(result2) else result2