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
相关推荐
LYFlied19 小时前
【每日算法】LeetCode 416. 分割等和子集(动态规划)
数据结构·算法·leetcode·职场和发展·动态规划
你撅嘴真丑1 天前
方格取数 矩阵取数游戏 -动态规划
算法·动态规划
leoufung1 天前
动态规划DP 自我提问模板
算法·动态规划
leoufung1 天前
LeetCode 64. Minimum Path Sum 动态规划详解
算法·leetcode·动态规划
leoufung1 天前
Word Break:深度理解 DP 前缀结束点的核心思想
算法·word·动态规划
冰西瓜6002 天前
贪心(一)——从动态规划到贪心 算法设计与分析 国科大
算法·贪心算法·动态规划
Sereinc.Y2 天前
【移动机器人运动规划(ROS)】03_ROS话题-服务-动作
c++·动态规划·ros·slam
玄同7652 天前
Python 异常捕获与处理:从基础语法到工程化实践的万字深度指南
开发语言·人工智能·python·自然语言处理·正则表达式·nlp·知识图谱
zhuzhihongNO12 天前
Java正则表达式持续更新
正则表达式·pattern.dotall·正则表达式贪婪模式·正则表达式惰性模式·java正则表达式