10. 正则表达式匹配

10. 正则表达式匹配

python 复制代码
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 False
            return True

        # 备忘录
        if memo[i][j] != -1:
            return memo[i][j]

        res = False
        if 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 = False

        memo[i][j] = res
        return res
相关推荐
汉克老师3 小时前
GESP2025年12月认证C++六级真题与解析(单选题8-15)
c++·算法·二叉树·动态规划·哈夫曼编码·gesp6级·gesp六级
Wuliwuliii4 小时前
贡献延迟计算DP
数据结构·c++·算法·动态规划·dp
多米Domi0111 天前
0x3f 第20天 三更24-32 hot100子串
java·python·算法·leetcode·动态规划
好想写博客1 天前
[动态规划]斐波那契数列
c++·算法·leetcode·动态规划
surtr12 天前
全源最短路封装模板(APSP,Floyd求最小环,Floyd求最短路,Johnson算法)
c++·算法·数学建模·动态规划·图论
上去我就QWER2 天前
你了解正则表达式中“?”的作用吗?
正则表达式
qq_317620312 天前
第09章-标准库与常用模块
正则表达式·标准库·collections模块·数据序列化·时间处理
weixin_461769402 天前
5. 最长回文子串
数据结构·c++·算法·动态规划
surtr12 天前
【算法自用】一些比较有趣的题目
算法·动态规划·概率论·图论
清水白石0082 天前
动态规划中的记忆化与缓存:原理、差异与 Python 实战指南
python·缓存·动态规划