-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregular_expression.py
40 lines (29 loc) · 1.24 KB
/
regular_expression.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
from typing import List
class Solution:
def isMatch(self, s: str, p: str) -> bool:
memo = [[None] * len(p) for _ in range(len(s) + 1)]
return self.checkMatch(s, p, 0, 0, memo)
def checkMatch(self, s: str, p: str, sIndex: int, pIndex: int, memo: List[List[int]]) -> bool:
if(sIndex == len(s) and pIndex == len(p)):
return True
if pIndex >= len(p):
return False
if memo[sIndex][pIndex] != None:
return memo[sIndex][pIndex]
memoMatch = False
match = sIndex < len(s) and (s[sIndex] == p[pIndex] or p[pIndex] == ".")
isNextStar = pIndex+1 < len(p) and p[pIndex+1] == "*"
if match:
if isNextStar:
memoMatch = self.checkMatch(s, p, sIndex, pIndex+2, memo) or self.checkMatch(s, p, sIndex+1, pIndex, memo)
else:
memoMatch = self.checkMatch(s, p, sIndex+1, pIndex+1, memo)
else:
if isNextStar:
memoMatch = self.checkMatch(s, p, sIndex, pIndex+2, memo)
else:
memoMatch = False
memo[sIndex][pIndex] = memoMatch
return memoMatch
sol = Solution().isMatch("aab", "c*a*b")
print(sol)