回溯
我理解的就是递归,一直在判断“*”的存在,最后递归得出结果
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p:
return not s
f= bool(s and p[0] in {s[0],'.'})
if len(p) >= 2 and p[1] == "*":
return self.isMatch(s, p[2:]) or f and self.isMatch(s[1:], p)
else:
return f and self.isMatch(s[1:], p[1:])
调包
python自带的包就很方便
毕竟re包就是专门负责正则化的
import re
class Solution:
def isMatch(self, s: str, p: str) -> bool:
return True if re.match(p+'$',s) else False
动态规划
我看了不少题解
主要是分为两个流派
dp[i][j]:s前i个和p前j个的结果
或 s[i:]和p[j:]的结果
最后我选择了后者
class Solution:
def isMatch(self, s: str, p: str) -> bool:
dp=[[False]*(len(p)+1) for i in range(len(s)+1)]
dp[-1][-1]=True
for i in range(len(s),-1,-1):
for j in range(len(p)-1,-1,-1):
f=i<len(s) and p[j] in {s[i],'.'}
if j<len(p)-1 and p[j+1]=='*':
dp[i][j]=dp[i][j+2] or f and dp[i+1][j]
else:
dp[i][j]=f and dp[i+1][j+1]
return dp[0][0]
这里我重点提及这一句代码
如果j正常范围并且j+1位是/*的话,那么dp[i][j]便等于后面那个式子
如果dp[i][j+2]是对的,那么直接赋值给了dp[i][j],那么这里/*代表的意思是0个前一位;如果是错的,则后面的式子变成f and dp[i+1][j],这里若都成立,则p[j]为".",或者p[j]=s[i]=s[i+1]成立,但无论哪种,dp[i][j]=dp[i+1][j]均成立。
if j<len(p)-1 and p[j+1]=='*':
dp[i][j]=dp[i][j+2] or f and dp[i+1][j]