逆向求解,防止暴栈。
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)