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
相关推荐
一水鉴天12 小时前
为AI聊天工具添加一个知识系统 之77 详细设计之18 正则表达式 之5
人工智能·正则表达式
xiaoshiguang31 天前
LeetCode:474.一和零
java·算法·leetcode·动态规划
维齐洛波奇特利(male)2 天前
(动态规划路径基础 最小路径和)leetcode 64
算法·leetcode·动态规划
南宫生2 天前
力扣动态规划-16【算法学习day.110】
算法·leetcode·动态规划
兮动人3 天前
正则表达式入门
正则表达式·正则表达式入门
南宫生3 天前
力扣动态规划-15【算法学习day.109】
java·学习·算法·leetcode·动态规划
xiaoshiguang33 天前
LeetCode:96.不同的二叉搜索树
java·算法·leetcode·动态规划
闻缺陷则喜何志丹3 天前
【C++动态规划 离散化】1626. 无矛盾的最佳球队|2027
c++·算法·leetcode·动态规划·最佳·球队·无矛盾
zfj3214 天前
java 正则表达式匹配Matcher 类
java·开发语言·正则表达式·find和matches
TPBoreas4 天前
ReUtil- 一个强大的正则表达式工具库
java·开发语言·正则表达式