题解 | #正则表达式匹配#

正则表达式匹配

https://www.nowcoder.com/practice/28970c15befb4ff3a264189087b99ad4

class Solution:
    def match(self , str: str, pattern: str) -> bool:
        if not pattern:
            return not str

        firstMatch = str and pattern[0] in {str[0], '.'}
        if len(pattern) >= 2 and pattern[1] == '*':
            return (self.match(str, pattern[2:]) or firstMatch and self.match(str[1:], pattern))
        else:
            return firstMatch and self.match(str[1:], pattern[1:])

解题思路

本题采用的是递归的思想。

  • 如果pattern不存在的话,就返回not str(当str不存在时,二者可以匹配上,返回True;都则返回False)。
  • 给firstMatch赋值,如果str还有,并且pattern[0]==str[0]或者是等于'.',则为True;否则为False。
  • 如果当前pattern长度大于等于2,并且pattern[1]等于'*',则返回(pattern[2:]后的匹配结果)或(firstMatch and str[1:]后的匹配结果);否则的话,返回firstMatch and (str[1:],pattern[1:]后的匹配结果)。

复杂度

  • 时间复杂度和空间复杂度都为O(mn)。
全部评论

相关推荐

03-05 17:03
已编辑
浙江工商大学 C++
陈好好wy:整体看下来有点空空的感觉,可以把每一段项目经历都再完善一下,然后用小标题的形式写个两到三条,目前看有点太简单了,不太能看出具体在这个项目里做了什么工作。还是要尽量把自己做的工作以量化的形式体现在简历上呢。
双非本科求职如何逆袭
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务