LintCode Q154 Regular Expression Matching in Python

  • Jinhai ZHOU
  • 7 Minutes
  • 2016年11月8日
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
class Solution:
"""
@param s: A string
@param p: A string includes "." and "*"
@return: A boolean
"""
def isMatch(self, s, p):
# write your code here
# Total Runtime: 627 ms
# 100% test cases passed
# remove duplicate * from p
# ex: c***a***b => c*a*b
p_len = 0
is_duplicate = False
pa = []
for c in p:
if c == '*':
if not is_duplicate:
pa.append(c)
is_duplicate = True
else:
pass
else:
pa.append(c)
is_duplicate = False
# create DP cache
len_pa = len(pa) + 1
len_s = len(s) + 1
match = [[False] * len_pa for row in xrange(len_s)]
# initialize
match[0][0] = True
# a*b* matches vide string
count = 0
for i in xrange(1, len_pa):
if pa[i - 1] == '*':
count -= 1
if count == 0:
match[0][i] = True
else:
count += 1
# main DP algorithme
for row in xrange(1, len_s):
for col in xrange(1, len_pa):
if pa[col - 1] == s[row - 1] or pa[col - 1] == '.':
match[row][col] = match[row - 1][col - 1]
elif pa[col - 1] == '*':
match[row][col] = match[row][col - 1] or match[row][col - 2] or match[row - 1][col -1]
if match[row][col] == False and s[row - 1] == s[row - 2]:
match[row][col] = match[row - 1][col]
return match[len(s)][len(pa)]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。