LeetCode 10. Regular Expression Matching

本文介绍了一种基于递归的正则表达式匹配算法,通过逆向求解避免了栈溢出的问题。该算法能够处理包含特殊字符如'.'和'*'的正则表达式,实现对字符串的有效匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

逆向求解,防止暴栈。

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        def regularMatch(s, sIndex, p, pIndex):
            if  pIndex < 0 and sIndex < 0:
                return True
            
            if sIndex >= 0 and pIndex >= 0 and (p[pIndex] == s[sIndex] or p[pIndex] == '.'):
                return regularMatch(s, sIndex-1, p, pIndex-1)
            
            if sIndex >= 0 and pIndex > 0 and p[pIndex] == '*' and (p[pIndex-1] == s[sIndex] or p[pIndex-1] == '.'):
                if regularMatch(s, sIndex-1, p, pIndex-2):
                    return True
                if regularMatch(s, sIndex-1, p, pIndex):
                    return True
            
            if pIndex > 0 and p[pIndex] == '*' and regularMatch(s, sIndex, p, pIndex-2):
                return True
                
            return False
            
        return regularMatch(s, len(s)-1, p, len(p)-1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值