10. 正则表达式匹配
class IsMatch:"""10. 正则表达式匹配https://leetcode.cn/problems/regular-expression-matching/description/"""def solution(self, s: str, p: str) -> bool:m, n = len(s), len(p)memo = [[-1] * n for _ in range(m)]return self.dp(s, 0, p, 0, memo)def dp(self, s: str, i: int, p: str, j: int, memo: list) -> bool:m, n = len(s), len(p)# base case 1# 模式串 p 匹配完了,那要看文本串 s 是否匹配完if j == n:return i == m# base case 2# 文本串 s 匹配完了,那模式串 p 一定是 字符 和 * 成对出现的if i == m:# 检查是否成对if (n - j) % 2 == 1:return False# 检查是否 x*y*z* 这种形式for k in range(j + 1, n, 2):if p[k] != '*':return Falsereturn True# 备忘录if memo[i][j] != -1:return memo[i][j]res = Falseif s[i] == p[j] or p[j] == '.':if j < n - 1 and p[j + 1] == '*':# 通配符匹配0次res = self.dp(s, i, p, j + 2, memo) or \self.dp(s, i + 1, p, j, memo) # 通配符匹配多次else:# 常规匹配1次res = self.dp(s, i + 1, p, j + 1, memo)else:if j < n - 1 and p[j + 1] == '*':# 通配符匹配0次res = self.dp(s, i, p, j + 2, memo)else:# 无法继续匹配res = Falsememo[i][j] = resreturn res