forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest-string-that-contains-three-strings.py
69 lines (62 loc) · 2.09 KB
/
shortest-string-that-contains-three-strings.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Time: O(l)
# Space: O(l)
# brute force, longest prefix suffix, kmp algorithm
class Solution(object):
def minimumString(self, a, b, c):
"""
:type a: str
:type b: str
:type c: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j != -1 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 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
if j+1 == len(pattern):
return i-j
return -1
def merge(a, b):
if KMP(b, a) != -1:
return b
prefix = getPrefix(b+'#'+a)
l = prefix[-1]+1 # longest prefix suffix length
return a+b[l:]
result = [merge(a, merge(b, c)), merge(a, merge(c, b)),
merge(b, merge(a, c)), merge(b, merge(c, a)),
merge(c, merge(a, b)), merge(c, merge(b, a))]
return min(result, key=lambda x: (len(x), x))
# Time: O(l^2)
# Space: O(l)
# brute force
class Solution2(object):
def minimumString(self, a, b, c):
"""
:type a: str
:type b: str
:type c: str
:rtype: str
"""
def merge(a, b):
if a in b:
return b
l = next((l for l in reversed(xrange(1, min(len(a), len(b)))) if a[-l:] == b[:l]), 0)
return a+b[l:]
result = [merge(a, merge(b, c)), merge(a, merge(c, b)),
merge(b, merge(a, c)), merge(b, merge(c, a)),
merge(c, merge(a, b)), merge(c, merge(b, a))]
return min(result, key=lambda x: (len(x), x))