def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
#dp定义为s的前i个字符是否匹配p的前j个字符
#base case dp[0][0] = True
m,n = len(s),len(p)
dp = [[False]*(n+1) for i in range(m+1)]
dp[0][0] = True
for j in range(1,n+1):
if p[j-1] == "*":
dp[0][j] = dp[0][j-2]
for i in range(1,m+1):
for j in range(1,n+1):
if s[i-1] == p[j-1] or p[j-1] == '.':
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == "*":
if s[i-1] != p[j-2] and p[j-2] != ".": #通配符x*这一项只能重复0次相当于删除j-1和j
dp[i][j] = dp[i][j-2]
else:
dp[i][j] = dp[i-1][j] or dp[i][j-2] #通配符也可以为0,也可以匹配k次
return dp[m][n]
leetcode10. 正则表达式匹配
最新推荐文章于 2024-11-04 17:55:03 发布