-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0010_regular-expression-matching.py
75 lines (66 loc) · 1.8 KB
/
0010_regular-expression-matching.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
70
71
72
73
74
75
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
s_index = 0
s_length = len(s)
p_index = 0
p_length = len(p)
while s_index < s_length and p_index < p_length:
p_c = p[p_index]
s_c = s[s_index]
p_next_c = p[p_index + 1] if p_index + 1 < p_length else None
if p_next_c == '*':
if p_c == '.' or p_c == s_c:
if self.isMatch(s[s_index:], p[p_index + 2:]):
# 剩余数据可匹配
p_index += 2
continue
else:
p_index += 2
continue
else:
if p_c == '.' or p_c == s_c:
p_index += 1
else:
return False
s_index += 1
# 还有剩余数据未匹配
if s_index != s_length:
return False
if p_index < p_length:
# 不是a*b*这样整对
if (p_length - p_index) % 2 != 0:
return False
while p_index < p_length:
p_next_c = p[p_index + 1] if p_index + 1 < p_length else None
if p_next_c != '*':
return False
else:
p_index += 2
return True
if __name__ == '__main__':
solution = Solution()
# example1
s = 'aab'
p = 'c*a*b'
# example2
# s = 'caab'
# p = 'c*a*b'
# example3
# s = 'mississippi'
# p = 'mis*is*p*.'
# example4
# s = 'aa'
# p = 'a*'
# example5
# s = 'aaa'
# p = 'a*a'
# example6
# s = 'aaa'
# p = 'ab*a*c*a'
b = solution.isMatch(s, p)
print(b)