1. 程式人生 > >【Leetcode】Python實現正則表示式匹配

【Leetcode】Python實現正則表示式匹配

給定一個字串 (s) 和一個字元模式 (p)。實現支援 ‘.’ 和 ‘*’ 的正則表示式匹配。

‘.’ 匹配任意單個字元。
‘*’ 匹配零個或多個前面的元素。
匹配應該覆蓋整個字串 (s) ,而不是部分字串。

說明:

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

示例 1:

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

示例 2:

輸入:
s = "aa"
p = "a*"
輸出: true
解釋: '*' 代表可匹配零個或多個前面的元素, 即可以匹配 'a'
。因此, 重複 'a' 一次, 字串可變為 "aa"

示例 3:

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

示例 4:

輸入:
s = "aab"
p = "c*a*b"
輸出: true
解釋: 'c' 可以不被重複, 'a' 可以被重複一次。因此可以匹配字串 "aab"

示例 5:

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

方法一:使用遞迴比較方便求解

class Solution(object):
    def
isMatch(self, s, p):
""" :type s: str :type p: str :rtype: bool """ # 判斷匹配規則是否為空 if p == "": # p為空的時候,判斷s是否為空,則知道返回True 或 False return s == "" # 判斷匹配規則是否只有一個 if len(p) == 1: # 判斷匹配字串長度是否為1,和兩者的第一個元素是否相同,或匹配規則使用.
return len(s) == 1 and (s[0] == p[0] or p[0] == '.') # 匹配規則的第二個字串不為*,當匹配字串不為空的時候 # 返回 兩者的第一個元素是否相同,或匹配規則使用. and 遞迴新的字串(去掉第一個字元的匹配字串 和 去掉第一個字元的匹配規則) if p[1] != "*": if s == "": return False return (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:], p[1:]) # 當匹配字串不為空 and (兩者的第一個元素是否相同 or 匹配規則使用.) while s and (s[0] == p[0] or p[0] == '.'): # 到了while迴圈,說明p[1]為*,所以遞迴呼叫匹配s和p[2:](*號之後的匹配規則) # 用於跳出函式,當s迴圈到和*不匹配的時候,則開始去匹配p[2:]之後的規則 if self.isMatch(s, p[2:]): return True # 當匹配字串和匹配規則*都能匹配的時候,去掉第一個字元成為新的匹配字串,迴圈 s = s[1:] # 假如第一個字元和匹配規則不匹配,則去判斷之後的是否匹配 return self.isMatch(s, p[2:]) if __name__ == '__main__': s = Solution() print(s.isMatch("aa", "a")) # false print(s.isMatch("aa", "aa")) # true print(s.isMatch("aaa", "aa")) # false print(s.isMatch("aa", "a*")) # true print(s.isMatch("aa", ".*")) # true print(s.isMatch("ab", ".*")) # true print(s.isMatch("aab", "c*a*b")) # true

方法二:簡化版,懶得寫註釋

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:])


if __name__ == '__main__':
    s = Solution()
    print(s.isMatch("aa", "a"))  # false
    print(s.isMatch("aa", "aa"))  # true
    print(s.isMatch("aaa", "aa"))  # false
    print(s.isMatch("aa", "a*"))  # true
    print(s.isMatch("aa", ".*"))  # true
    print(s.isMatch("ab", ".*"))  # true
    print(s.isMatch("aab", "c*a*b"))  # true