原文要求如下:
Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
isMatch("aaaa","ab*a*c*a") → true #自己加的
解法有兩種
遞歸
遞歸想法比較簡單代碼也比較清楚,但耗時很長復雜度是指數級別
考慮遞歸思想時,只需要考慮終結情況,和當前情況,其他的任由遞歸完成
當前情況的考慮如下:
因為*
號是最復雜的情況甚至可以發生0次于是分成兩種情況分別考慮:p[1] 為 *
和 p[1] 不為 *
-
p[1] != *
時:說明當前p[0]不會發生0-n次的變化直接對比就可以,剩下的交給遞歸 -
s[0] == p[0]
判等(這個相等包含了.
的情況,后面相同) - 遞歸判斷
isMatch(s[1:],p[1:])
兩個子串 -
p[1] == *
時:說明當前p[0]會發生0-n次的變化,而且都是有效的 - 假設發生 0次 :那么直接將p[0,1]跳過進行遞歸
isMatch(s,p[2:])
- 假設發生 1次以上:那么得先判等,然后s+1進行遞歸
s[0]==p[0] and isMatch(s[1:],p)
好了所有情況都考慮好了,就可以直接上代碼了,遞歸思想還是比較簡單,直接看代碼可能比看上述文字更加簡單直接。
talk is cheep show me code:
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if p=="":
return s==""
if len(p)>1 and '*' == p[1]:
return self.isMatch(s, p[2:]) or ((s!="" and (s[0]==p[0] or '.'==p[0])) and self.isMatch(s[1:], p))
else:
return (s!="" and (s[0]==p[0] or '.'==p[0])) and self.isMatch(s[1:], p[1:])
動態規劃
動態規劃處理這個問題,更加有效,復雜度為 O(N*M)
.但是不同于遞歸直接看代碼,動態規劃我簡直還是先看狀態公式更加明了。
用dp[i][j]來代表 s[0:i] 與 p[0:j] 是否匹配,初始化 dp[0][0]=1(空串匹配空串)
$$(由于簡書不支持latex只好這樣子了)
dp[i][j]=dp[i][j-1], ????????條件 p[j-1]=* ,是考慮到 * 只重復一次
dp[i][j]=dp[i][j-2], ????????條件 p[j-1]=* ,是考慮到 * 只重復0次
dp[i][j]=dp[i-1][j] && S[i-1]==P[j-2],條件 p[j-1]=* ,是考慮到 * 重復了多次
dp[i][j]=dp[i-1][j-1] && S[i-1]=P[j-1] ,條件 p[j-1]!=*
$$
從狀態公式基本也能看的明白,要計算 dp[i][j] 的值,要分成兩個情況,兩個情況分別處理后就能將dp填滿,則最后的結果就是 dp[len(s)][len(p)]的值
如果看公式還是有點不清楚,來舉個栗子:s="ccd" , p="a*c*d"
dp的矩陣情況如下:
# | ^ | a | * | c | * | d |
---|---|---|---|---|---|---|
^ | 1 | 0 | 1 | 0 | 1 | 0 |
c | 0 | 0 | 0 | 1 | <font color=blue>1</font> | 0 |
c | 0 | 0 | 0 | 0 | <font color=red>1</font> | 0 |
d | 0 | 0 | 0 | 0 | 0 | 1 |
藍色那個是因為 dp[i][j-1]=1 所以這個*只重復1的匹配結果,因此可以為 1
紅色那個是因為 dp[i-1][j]=1 && s[i-1]==p[j-2] 代表已經被重復過了,不止1次,但依然可以被繼續重復下去
talk is cheep show me code:
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
lens = len(s)
lenp = len(p)
dp = [[False for col in range(lenp+1)] for row in range(lens+1)]
dp[0][0] = True
for j in range(1, lenp+1):
dp[0][j] = p[j-1]=='*' and dp[0][j-2]==1
for i in range(1, lens+1):
for j in range(1, lenp+1):
if p[j-1] == '*':
dp[i][j] = dp[i][j-2] or dp[i][j-1] or (dp[i-1][j] and (s[i-1]==p[j-2] or '.'==p[j-2]))
else:
dp[i][j] = dp[i-1][j-1] and (s[i-1]==p[j-1] or '.'==p[j-1])
return dp[lens][lenp]