-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path10_RegularExpressionMatching.py
executable file
·68 lines (59 loc) · 1.89 KB
/
10_RegularExpressionMatching.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def isMatch(self, s, p):
"""
Dynamic Programming
dp[i][j] represents isMatch(p[0...i], s[0...j]), default is False;
dp[i][-1] represents isMatch(p[0...i], "")
dp[-1][j] represents isMatch("", s[0...j])
"""
if not s:
# .*.*.*.* Return True, others return False.
if len(p) % 2 != 0:
return False
for k in range(1, len(p), 2):
if p[k] != "*":
return False
return True
# dp = [[False] * (len(s)+1)] * (len(p)+1)
dp = [[False for col in range(len(s) + 1)]
for row in range(len(p) + 1)]
dp[-1][-1] = True
for i in range(len(p)):
for j in range(len(s)):
"""
p[i] is "*", so dp[i][j] =
1. dp[i-2][j] # * matches 0 element in s;
2. dp[i-2][j-1] # * matches 1 element in s;
3. dp[i][j-1] # * matches more than one in s.
"""
if p[i] == "*":
m_0 = dp[i - 2][j]
m_1 = (p[i - 1] == "." or p[i - 1] == s[j]) and dp[i - 2][j - 1]
m_more = (p[i - 1] == "." or p[i - 1] == s[j]) and dp[i][j - 1]
dp[i][j] = m_0 or m_1 or m_more
# p[i] matches "" is equal p[i-2] matches "".
dp[i][-1] = dp[i - 2][-1]
else:
dp[i][j] = (dp[i - 1][j - 1] and
(p[i] == s[j] or p[i] == "."))
# p[i] doesn't match ""
dp[i][-1] = False
return dp[len(p) - 1][len(s) - 1]
"""
"aaa"
"ab*a"
""
"c*c*"
"aaa"
"aaaa"
"aaabc"
"a*bc"
"aab"
"c*a*b"
"ab"
".*c"
"aaaaabaccbbccababa"
"a*b*.*c*c*.*.*.*c"
"""