1. 程式人生 > 實用技巧 >10. 正則表示式匹配

10. 正則表示式匹配

給你一個字串s和一個字元規律p,請你來實現一個支援 '.'和'*'的正則表示式匹配。

'.' 匹配任意單個字元
'*' 匹配零個或多個前面的那一個元素
所謂匹配,是要涵蓋整個字串s的,而不是部分字串。

說明:

s可能為空,且只包含從a-z的小寫字母。
p可能為空,且只包含從a-z的小寫字母,以及字元.和*。
示例 1:

輸入:
s = "aa"
p = "a"
輸出: false
解釋: "a" 無法匹配 "aa" 整個字串。
示例 2:

輸入:
s = "aa"
p = "a*"
輸出: true
解釋:因為 '*' 代表可以匹配零個或多個前面的那一個元素, 在這裡前面的元素就是 'a'。因此,字串 "aa" 可被視為 'a' 重複了一次。
示例3:

輸入:
s = "ab"
p = ".*"
輸出: true
解釋:".*" 表示可匹配零個或多個('*')任意字元('.')。
示例 4:

輸入:
s = "aab"
p = "c*a*b"
輸出: true
解釋:因為 '*' 表示零個或多個,這裡 'c' 為 0 個, 'a' 被重複一次。因此可以匹配字串 "aab"。
示例 5:

輸入:
s = "mississippi"
p = "mis*is*p*."
輸出: false

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/regular-expression-matching
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

recursion

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p:return len(s)==0
        if len(p)==1 or p[1]!='*':
            if len(s)<1 or p[0]!='.' and s[0]!=p[0]:
                return False
            return self.isMatch(s[1:],p[1:])
        else:
            l
=len(s) i=-1 while i<l and (i<0 or p[0]=='.' or p[0]==s[i]): if self.isMatch(s[i+1:],p[2:]): return True i+=1 return False

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        if not p:return len(s)==0
        head_match=bool(s) and (p[0]==s[0] or p[0]=='.')
        if len(p)>=2 and p[1]=='*':
            return head_match and self.isMatch(s[1:],p) or self.isMatch(s,p[2:])
        else:
            return head_match and self.isMatch(s[1:],p[1:])
        return False

dynamic programming

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
            dic={}
            def dp(i,j):
                if (i,j) in dic:
                    return dic[(i,j)]
                if j==len(p):
                    return i==len(s)
                head_match=i<len(s) and p[j] in [s[i],'.']
                if j<=len(p)-2 and p[j+1]=='*':
                    dic[(i,j)]=dp(i,j+2) or (head_match and dp(i+1,j))
                else:
                    dic[(i,j)]=head_match and dp(i+1,j+1)
                return dic[(i,j)]
            return dp(0,0)