1 题目描述
来源:力扣(LeetCode)
请实现一个函数用来匹配包含’. ‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但与"aa.a"和"ab*a"均不匹配。
2 代码实现(Python3)
# 法1
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p:return not s
if len(p)>1 and p[1]=='*':
return self.isMatch(s,p[2:]) or (s!='' and (s[0]==p[0] or p[0]=='.') and self.isMatch(s[1:],p)) or (s!='' and (s[0]==p[0] and p[0]=='.') and self.isMatch(s[1:],p[2:]))
if s and (s[0]==p[0] or p[0]=='.'):return self.isMatch(s[1:],p[1:])
return False
# 法2
class Solution:
def isMatch(self, s: str, p: str) -> bool:
s, p = '#'+s, '#'+p
m, n = len(s), len(p)
dp = [[False]*n for _ in range(m)]
dp[0][0] = True
for i in range(m):
for j in range(1, n):
if i == 0:
dp[i][j] = j > 1 and p[j] == '*' and dp[i][j-2]
elif p[j] in [s[i], '.']:
dp[i][j] = dp[i-1][j-1]
elif p[j] == '*':
dp[i][j] = j > 1 and dp[i][j-2] or p[j-1] in [s[i], '.'] and dp[i-1][j]
else:
dp[i][j] = False
return dp[-1][-1]
深入了解复杂度:数据分析学习总结笔记11:空间复杂度和时间复杂度