Skip to content

Commit e08f06c

Browse files
authored
Create substring-matching-pattern.py
1 parent c702d74 commit e08f06c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Python/substring-matching-pattern.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Time: O(n + m)
2+
# Space: O(m)
3+
4+
# kmp
5+
class Solution(object):
6+
def hasMatch(self, s, p):
7+
"""
8+
:type s: str
9+
:type p: str
10+
:rtype: bool
11+
"""
12+
def getPrefix(pattern):
13+
prefix = [-1]*len(pattern)
14+
j = -1
15+
for i in xrange(1, len(pattern)):
16+
while j+1 > 0 and pattern[j+1] != pattern[i]:
17+
j = prefix[j]
18+
if pattern[j+1] == pattern[i]:
19+
j += 1
20+
prefix[i] = j
21+
return prefix
22+
23+
def KMP(text, pattern, i):
24+
prefix = getPrefix(pattern)
25+
j = -1
26+
for i in xrange(i, len(text)):
27+
while j+1 > 0 and pattern[j+1] != text[i]:
28+
j = prefix[j]
29+
if pattern[j+1] == text[i]:
30+
j += 1
31+
if j+1 == len(pattern):
32+
return i-j
33+
return -1
34+
35+
i = 0
36+
for x in p.split('*'):
37+
if not x:
38+
continue
39+
i = KMP(s, x, i)
40+
if i == -1:
41+
return False
42+
i += len(x)
43+
return True
44+

0 commit comments

Comments
 (0)