Skip to content

Commit 4fb4e44

Browse files
authored
Update shortest-matching-substring.py
1 parent 8be372f commit 4fb4e44

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Python/shortest-matching-substring.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,64 @@
33

44
# kmp, two pointers (three pointers)
55
class Solution(object):
6+
def shortestMatchingSubstring(self, s, p):
7+
"""
8+
:type s: str
9+
:type p: str
10+
:rtype: int
11+
"""
12+
INF = float("inf")
13+
def getPrefix(pattern):
14+
prefix = [-1]*len(pattern)
15+
j = -1
16+
for i in xrange(1, len(pattern)):
17+
while j+1 > 0 and pattern[j+1] != pattern[i]:
18+
j = prefix[j]
19+
if pattern[j+1] == pattern[i]:
20+
j += 1
21+
prefix[i] = j
22+
return prefix
23+
24+
def KMP(text, pattern):
25+
if not pattern:
26+
for i in xrange(len(text)+1):
27+
yield i
28+
return
29+
prefix = getPrefix(pattern)
30+
j = -1
31+
for i in xrange(len(text)):
32+
while j+1 > 0 and pattern[j+1] != text[i]:
33+
j = prefix[j]
34+
if pattern[j+1] == text[i]:
35+
j += 1
36+
if j+1 == len(pattern):
37+
yield i-j
38+
j = prefix[j]
39+
40+
a, b, c = p.split('*')
41+
n = len(s)
42+
la, lb, lc = len(a), len(b), len(c)
43+
result = INF
44+
j = k = 0
45+
jt = KMP(s, b)
46+
kt = KMP(s, c)
47+
for i in KMP(s, a):
48+
while j != -1 and j < i+la:
49+
j = next(jt, -1)
50+
if j == -1:
51+
break
52+
while k != -1 and k < j+lb:
53+
k = next(kt, -1)
54+
if k == -1:
55+
break
56+
result = min(result, (k+lc)-i)
57+
return result if result != INF else -1
58+
59+
60+
# Time: O(n + m)
61+
# Space: O(n + m)
62+
# kmp, two pointers (three pointers)
63+
class Solution2(object):
664
def shortestMatchingSubstring(self, s, p):
765
"""
866
:type s: str

0 commit comments

Comments
 (0)