【LeetCode】Regular Expression Matching 正则表达式匹配

题目来源:https://leetcode-cn.com/problems/regular-expression-matching/

题目描述

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

给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。

‘.’ 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 *.

所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。

说明:

s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。

示例

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

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "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

解题思路

在这里插入图片描述

算法实现

Python3

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p: return not s
        #若p为空,s不为空,则返回FALSE,
        #若p为空,s也为空,则返回TRUE
        first_match=bool(s) and p[0] in {s[0],'.'}
        #如果s的第一个元素符合p,或者是个'.',则first_match=TRUE
        if len(p)>=2 and p[1]=='*': #如果p中第二个是'*'
            # 假设s中匹配0次,则跳过该字符和'*'
            return self.isMatch(s, p[2:]) \
                   or first_match and self.isMatch(s[1:],p) 
                   # 假设s中匹配至少1次,则跳过1个字符
        else:
            return first_match and self.isMatch(s[1:],p[1:])
            #如果p中没有'#',则按正常的来

参考资料

https://leetcode-cn.com/problems/regular-expression-matching/solution/ji-yu-guan-fang-ti-jie-gen-xiang-xi-de-jiang-jie-b/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值