记忆化递归_or_DP_Hard_10_正则表达式匹配

文章目录

  • 题目描述
  • 思路
    • 方法一:DP
    • 方法二:递归

题目描述

记忆化递归_or_DP_Hard_10_正则表达式匹配_第1张图片

思路

方法一:DP

Reference
记忆化递归_or_DP_Hard_10_正则表达式匹配_第2张图片
记忆化递归_or_DP_Hard_10_正则表达式匹配_第3张图片
记忆化递归_or_DP_Hard_10_正则表达式匹配_第4张图片

  • 注意特判:s="",p="a*b*" 需要返回True
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        m, n = len(s)+1, len(p)+1  # row, column
        dp = [[0]*n for _ in range(m)]
        dp[0][0] = 1
        if len(p)>1 and p[0]!='*' and p[1] == '*':
            dp[0][2] = 1
        index = 1
        while index < len(p):
            if p[index] == '*' and p[index-1] != '*':
                dp[0][index+1] = 1
                index += 2
            else: break
        for i in range(1, m):
            for j in range(1, n):
                if s[i-1] == p[j-1] or p[j-1] == '.':
                    dp[i][j] = dp[i-1][j-1]
                elif p[j-1] == '*':
                    if p[j-2] != '.' and p[j-2] != s[i-1]:
                        dp[i][j] = dp[i][j-2]
                    else:
                        dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i][j-2])
        return True if dp[-1][-1] else False

方法二:递归

  • 暴力递归
class Solution:
    # 暴力递归
    def isMatch(self, text, pattern) -> bool:
        if not pattern: return not text

        first = bool(text) and pattern[0] in {text[0], '.'}

        if len(pattern) >= 2 and pattern[1] == '*':
            return self.isMatch(text, pattern[2:]) or (first and self.isMatch(text[1:], pattern))
        else:
            return first and self.isMatch(text[1:], pattern[1:])
  • 记忆化递归
class Solution:
    # 带备忘录的递归
    def isMatch(self, text, pattern) -> bool:
        memo = dict() # 备忘录
        def dp(i, j):
            if (i, j) in memo: return memo[(i, j)]
            if j == len(pattern): return i == len(text)

            first = i < len(text) and pattern[j] in {text[i], '.'}

            if j <= len(pattern) - 2 and pattern[j + 1] == '*':
                ans = dp(i, j + 2) or (first and dp(i + 1, j))
            else:
                ans = first and dp(i + 1, j + 1)

            memo[(i, j)] = ans
            return ans
        return dp(0, 0)

你可能感兴趣的:(LeetCode题解,leetcode,正则表达式,字符串,python)