leetcode 10. 正則表達式匹配
題意:
給你一個字符串 s 和一個字符規律 p,請你來實現一個支持 ‘.’ 和 ‘*’ 的正則表達式匹配。
‘.’ 匹配任意單個字符
‘*’ 匹配零個或多個前面的那一個元素
所謂匹配,是要涵蓋 整個 字符串 s的,而不是部分字符串。
思路:
這個匹配的過程實際上就是一個回溯的搜索(暴力), 如果是這個思路,難點就是這個寫法,然後注意這個過程具有子結構
的特點,所以可以用記憶化搜索來寫。
先看第一種回溯思路寫法,實際看成一個自上而下的搜索,理清楚幾個搜索條件的分界點:
- 當字符規律p爲空時,s必須爲空。
- 接着判斷當p[1] == '*'時候,有兩個不同回溯方向,一個可以考慮當前當前匹配零個,一個考慮p[0]匹配到當前s[0]。
- 如果p[1]!=’*’,那只有考慮p[0]匹配掉當前s[0]。
最初我的(醜陋)的寫法:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p: return not s
if len(p) >=2 and p[1] == '*':
return self.isMatch(s, p[2:]) or (len(s)>0 and (p[0] == s[0] or p[0] =='.')) and self.isMatch(s[1:], p)
elif len(s)>0 and (p[0] == s[0] or p[0] =='.'):
return self.isMatch(s[1:], p[1:])
else : return False
看了官方題解python(優美)寫法:
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:])
這種不帶記憶化操作的寫法時間是1464 ms
。
回溯寫法 C++
class Solution {
public:
bool isMatch(string s, string p) {
if(p.size() ==0) return s.size() == 0 ;
bool first_match = s.size()>0 && (p[0] == s[0]||p[0] == '.');
if(p.size()>=2&&p[1]=='*'){
return (isMatch(s,p.substr(2)) || first_match && isMatch(s.substr(1), p));
}
else return first_match && isMatch(s.substr(1), p.substr(1));
}
};
c++不帶記憶化操作時限是416 ms
。
根據上面分析,這題回溯的過程具有子結構的特點,我們可以用一個數組保存每一次回溯搜索狀態的值,俗稱記憶化操作。
這裏用dp(i,j)
表示 s[i:]與 p[j:]匹配的情況,則可以將回溯自上而下搜索的過程加入保存每個狀態的操作:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
memo = {}
def dp(i, j):
if (i,j) not in memo:
if j == len(p):
ans = True if i == len(s) else False
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)
memo[i,j] = ans
return memo[i, j]
return dp(0,0)
這種寫法時間複雜度是O(len(s)* len(p))
, 時限是40ms
,超過97.08%的用戶。
回溯實際上看成自上朝下的搜索方式,這題又有子結構的特點,設定好狀態表示dp(i,j)
後,我們自然可以考慮它狀態轉移方程,寫成一種自下朝上的搜索過程,也可以說是動態規劃的思想。
這裏的dp(i,j)仍然表示 s[i:]和p[j:]是否匹配。
class Solution:
def isMatch(self, s: str, p: str) -> bool:
n, m = len(s), len(p)
print(n,m)
dp = [[False] * (m+1) for _ in range(n+1)]
print(dp)
dp[n][m] = True
for i in range(n,-1,-1):
for j in range(m-1, -1,-1):
first_match = i<n and p[j] in {s[i], '.'}
if j+1 < m and p[j+1] =='*':
dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j]
else :
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]
如果dp(i,j)表示s[:i]和p[:j]是否匹配,則轉移方程以及寫法都需要改變:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
n, m = len(s), len(p)
print(n,m)
dp = [[False] * (m+1) for _ in range(n+1)]
dp[0][0] = True
for i in range(0, n+1 ,1):
for j in range(1, m+1 ,1):
first_match = i>0 and p[j-1] in {s[i-1], '.'}
if j>=2 and p[j-1] =='*':
dp[i][j] = dp[i][j-2] or (i>0 and p[j-2] in {s[i-1],'.'}) and dp[i-1][j]
else :
dp[i][j] = first_match and dp[i-1][j-1]
#print(dp)
return dp[n][m]
leetcode 44
這道題就相當於是leetcode10簡化版,‘?’作用和’.‘一樣,不同是’*'可以匹配任意字符串。
所以只需要在leetcode10代碼基礎上把狀態轉移的條件修改一下:
自底向下:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
memo = {}
def dp(i, j):
if (i,j) not in memo:
if j == len(p):
ans = True if i == len(s) else False
else :
first_match = i< len(s) and p[j] in {s[i], '?', '*'}
if p[j] == '*':
ans = dp(i,j+1) or first_match and dp(i+1,j)
else :
ans = first_match and dp(i+1, j+1)
memo[i,j] = ans
return memo[i, j]
return dp(0,0)
自底向上:
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
dp = [[False]* (n+1) for _ in range(m+1)]
dp[m][n] = True
for i in range(m, -1,-1):
for j in range(n-1, -1,-1):
first_match = i < m and p[j] in (s[i], '?')
if p[j] == '*':
dp[i][j] = dp[i][j+1] or i<m and dp[i+1][j]
else:
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]