解题思路:采用递归的思路,比较复杂的点在于将所有的情况都要考虑到。首先因为p是模式串会出现正则表达式*
和.
,所以所有的情况我们都已模式串P为出发点。具体的情况可以用下面的流程图表示:
按照流程图可以写出下面的代码:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
lens = len(s)
lenp = len(p)
if lenp == 0:
if lens == 0:
return True
return False
if lenp == 1:
if lens > 0 and (s[0] == p[0] or p[0] == '.'):
return self.isMatch(s[1:], p[1:])
return False
else:
if p[1] == '*':
if lens > 0 and (s[0] == p[0] or p[0] == '.'):
return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p)
return self.isMatch(s, p[2:])
else:
if lens > 0 and (s[0] == p[0] or p[0] == '.'):
return self.isMatch(s[1:], p[1:])
return False
思路二:动态规划,用dp[i][j]
表示s[i:]和p[j:]
是否匹配,然后可以根据s[i]和p[j]是否匹配以及p[j+1]是否为’*'得到不同的转态转移方程,代码如下:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
lenp = len(p)
lens = len(s)
dp = [[False] * (lenp + 1) for i in range(lens+1)]
dp[-1][-1] = True
for i in range(lens, -1, -1):
for j in range(lenp-1, -1, -1):
first_match = i < lens and (s[i] == p[j] or p[j] == '.')
if j + 1 < lenp and p[j+1] == '*':
if first_match:
dp[i][j] = dp[i+1][j] or dp[i][j+2]
else:
dp[i][j] = dp[i][j+2]
else:
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]