1. 題目
請實現一個函數用來匹配包含’.‘和’‘的正則表達式。模式中的字符’.‘表示任意一個字符,二’'表示它前面的字符可以出現任意次(含0次)。在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串"aaa"與模式"a.a"和"abaca"匹配,但與"aa.a"和"ab*a"均不匹配。
2. 解題思路
不說了直接向大佬學習吧! 詳解 回溯+動態規劃
3. 代碼實現
3.1 回溯
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],'.'})
# 如果 p 第二個字母是 *
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:])
3.2 動態規劃
class Solution:
def isMatch(self, s: str, p: str) -> bool:
# 邊界條件,考慮 s 或 p 分別爲空的情況
if not p: return not s
if not s and len(p) == 1: return False
m, n = len(s) + 1, len(p) + 1
dp = [[False for _ in range(n)] for _ in range(m)]
# 初始狀態
dp[0][0] = True
dp[0][1] = False
for c in range(2, n):
j = c - 1
if p[j] == '*':
dp[0][c] = dp[0][c - 2]
for r in range(1,m):
i = r - 1
for c in range(1, n):
j = c - 1
if s[i] == p[j] or p[j] == '.':
dp[r][c] = dp[r - 1][c - 1]
elif p[j] == '*': # ‘*’前面的字符匹配s[i] 或者爲'.'
if p[j - 1] == s[i] or p[j - 1] == '.':
dp[r][c] = dp[r - 1][c] or dp[r][c - 2]
else: # ‘*’匹配了0次前面的字符
dp[r][c] = dp[r][c - 2]
else:
dp[r][c] = False
return dp[m - 1][n - 1]
4. 總結
傷不起
5. 參考文獻
[1] 劍指offer叢書
[2] 劍指Offer——名企面試官精講典型編程題