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
相关推荐
样例过了就是过了2 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
样例过了就是过了8 小时前
LeetCode热题100 最小路径和
c++·算法·leetcode·动态规划
承渊政道10 小时前
【动态规划算法】(子数组系列问题建模与解题思路精讲)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
承渊政道10 小时前
【动态规划算法】(子序列问题解题框架与典型案例)
数据结构·c++·学习·算法·leetcode·macos·动态规划
样例过了就是过了1 天前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
minji...1 天前
算法题 动态规划
算法·动态规划
小糖学代码1 天前
LLM系列:1.python入门:16.正则表达式与文本处理 (re)
人工智能·pytorch·python·深度学习·神经网络·正则表达式
Irene19911 天前
(课堂笔记)SQL 临时表、视图、正则表达式
正则表达式·视图·临时表
样例过了就是过了1 天前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划
穿越临界点1 天前
动态规划(DP)
算法·动态规划·贝尔曼