1. 程式人生 > 其它 >Leetcode10:正則表示式匹配python實現

Leetcode10:正則表示式匹配python實現

技術標籤:Leetcode字串正則表示式pythonleetcode

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

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

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