题解简直精妙。。。。。。虽然非常费时间,回头再补上省时间的方法,想必也很精妙
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)