python刷题之.正则表达式匹配

题解简直精妙。。。。。。虽然非常费时间,回头再补上省时间的方法,想必也很精妙

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p:return not s
        first_match=bool(s) and p[0] in {s[0],'.'}
        if len(p) >= 2 and p[1] == '*':
            return (self.isMatch(s,p[2:])) or first_match and (self.isMatch(s[1:],p))
        else :
            return first_match and (self.isMatch(s[1:],p[1:]))
        

这个方法确实是省时间啊,不过在内存方面就占用很多了 啊,难道是保存(i,j)弄得么?不过还是精妙啊,全程都是疯狂看答案啊,感觉自己想全是有难度,其实不光是需要把代码敲出来,更重要的是把算法的逻辑,方法搞懂,然后通过代码表达出来。

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        myDict={}
        def dp(i,j):
            if (i,j) not in myDict:
                if j==len(p):
                    ans= i==len(s)
                else:
                    first_match= i<len(s) and p[j] in {s[i], '.'}
                    if j+1<len(p) and p[j+1] == '*':
                        ans= dp(i,j+2) or first_match and dp(i+1,j) 
                    else:
                        ans= first_match and dp(i+1,j+1)
                myDict[i,j]=ans
            return myDict[i,j]       
        return dp(0,0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值