class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
dp = [False] * (n+1)
# 初始化
dp[0] = True
for j in range(1, n+1):
if p[j-1] == '*':
dp[j] = dp[j-2]
# 状态更新
for i in range(1, m+1):
dp2 = [False] * (n+1) # 滚动数组
for j in range(1, n+1):
if s[i-1] == p[j-1] or p[j-1] == '.':
dp2[j] = dp[j-1]
elif p[j-1] == '*':
if s[i-1] != p[j-2] and p[j-2] != '.':
dp2[j] = dp2[j-2]
else:
dp2[j] = dp2[j-2] | dp[j]
dp = dp2 # 滚动数组
if sum(dp) == 0: # 提前结束
return False
return dp[n]