LeetCode 10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

思路:

两个字符串匹配类问题,通常使用匹配型动态规划

一般动态解题步骤:

1. 确定状态

dp[i][j]表示前i个p字符与前j个s字符是否匹配

2. 转移方程

因为存在'.'和'*'两个特殊字符,需要分类讨论:

  • 如果p[j - 1]不是'*', 那只要s与p当前字符相同或者p的当前字符为'.', 因为'.'可以匹配任何非空单个字符, 即dp[i][j] = dp[i - 1][j - 1] and (s[i - 1] == p[j - 1] or p[j - 1] == '.')
  • 如果p[j - 1]是'*', 可以分两种情况讨论:1. x*匹配0个字符,dp[i][j] = dp[i][j - 2]; 2. x*匹配1-N个字符,p的前一字符与当前s字符相同,并且上一字符串是匹配的(dp[i -1][j]), dp[i][j] = dp[i][j- 2] or (s[i - 1] == p[j - 2] or p[j - 2] == '.' and dp[i - 1][j])

3. 初始条件和边界条件

dp[0][0] = True # 空字符串可以匹配空字符串

对于第一行的处理,dp[0][j] = dp[0][j - 2] if p[j - 1] == '*' else False

4. 计算顺序

i: 1 - len(s)

j: 1 - len(p)

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        rows = len(s)
        columns = len(p)

        dp = [[False for _ in range(columns + 1)] for _ in range(rows + 1)]

        dp[0][0] = True

        # 初始化第一行
        for column in range(1, columns + 1):
            if p[column - 1] == "*":
                dp[0][column] = dp[0][column - 2]

        for r in range(1, rows + 1):
            for c in range(1, columns + 1):
                if p[c - 1] == '*':
                    dp[r][c] = dp[r][c - 2] or ((s[r - 1] == p[c - 2] or p[c - 2] == '.') and dp[r - 1][c])
                else:
                    dp[r][c] = dp[r - 1][c - 1] and (s[r - 1] == p[c - 1] or p[c - 1] == '.')
        return dp[-1][-1]

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值