Skip to content

Commit eae7c58

Browse files
committed
正则表达式匹配
1 parent b849e70 commit eae7c58

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

regular_expression_matching.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param s: A string
6+
@param p: A string includes "." and "*"
7+
@return: A boolean
8+
"""
9+
def isMatch(self, s, p):
10+
# write your code here
11+
m, n = len(s), len(p)
12+
dp = [[False for _ in xrange(n + 1)] for _ in xrange(m + 1)]
13+
dp[0][0] = True # 两个长度为0的字符串一定匹配
14+
# 处理s长度为0的可能出现匹配情况
15+
for j in xrange(1, n + 1): # j索引p
16+
dp[0][j] = (j > 1) and (p[j - 1] == '*') and dp[0][j - 2]
17+
for j in xrange(1, n + 1): # j索引p
18+
for i in xrange(1, m + 1): # i索引s
19+
if (j > 1) and (p[j - 1] == '*'):
20+
'''
21+
在两种情况下匹配。
22+
条件1:dp[i][j - 2] = True
23+
条件2:以下两个条件同时满足
24+
- dp[i - 1][j] = True
25+
- s[i - 1] == p[j - 2]或者p[j - 2] == '.'
26+
'''
27+
dp[i][j] = (dp[i][j - 2]) or (dp[i - 1][j] and ((s[i - 1] == p[j - 2]) or (p[j - 2] == '.')))
28+
else:
29+
# 只有当dp[i - 1][j - 1] = True时,判断两个字符是否匹配。
30+
dp[i][j] = dp[i - 1][j - 1] and ((s[i - 1] == p[j - 1]) or (p[j - 1] == '.'))
31+
return dp[m][n]

0 commit comments

Comments
 (0)