defisMatch(s: str, p: str) -> bool: # .*表示任意字符串都可以匹配了 defoptimizePattern(p): j = 0 while j < len(p)-1: if p[j+1] == '*': if j+3 <= len(p)-1and p[j:j+2] == p[j+2:j+4]: p = p[:j+2] + p[j+4:] continue j += 1# 配合下一句,实现 j+=2 j += 1 return p
@debugHelper defdp(s,p): n,m = len(s), len(p) if m == 0: return n == 0 if n == 0: if m == 1or p[1] != '*': returnFalse return dp(s,p[2:]) if m == 1or p[1] !='*': if s[0] == p[0] or p[0] == '.': return dp(s[1:],p[1:]) returnFalse # .* 或者 any char with * if p[0] == '.'or s[0] == p[0]: return dp(s,p[2:]) or dp(s[1:],p) # 匹配或者不匹配 else: return dp(s,p[2:]) # 不相同,只能不匹配了
p = optimizePattern(p) return dp(s,p)
s = "aab" p = 'c*a*b' res = isMatch(s,p) print(res)