LeetCode_Everyday:010 Regular Expression Matching

LeetCode_Everyday:010 Regular Expression Matching


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

給你一個字符串 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

代碼

方法一: 回溯

執行用時 :1512 ms, 在所有 Python3 提交中擊敗了19.97%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了6.82%的用戶

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: 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:])
    
"""
For Example:    input:   x = -121
               output:   False
"""
s = "mississippi"
p = "mis*is*p*."
                
solution = Solution()
result = solution.isMatch(s, p)
print('輸出爲:', result)    # False

方法二: 動態規劃

執行用時 :56 ms, 在所有 Python3 提交中擊敗了86.07%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了6.82%的用戶

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        cache = [[False]*(len(s)+1) for _ in range(len(p)+1)]
        cache[0][0] = True
        for i in range(1, len(p)):
            cache[i+1][0] = cache[i-1][0] and p[i] == '*'
        for i in range(len(p)):
            for j in range(len(s)):
                if p[i] == '*':
                    cache[i+1][j+1] = cache[i][j+1] or cache[i-1][j+1]
                    if p[i-1] == s[j] or p[i-1] == '.':
                        cache[i+1][j+1] |= cache[i+1][j]
                else:
                    cache[i+1][j+1] = cache[i][j] and (p[i] == s[j] or p[i] == '.')
        return cache[-1][-1]
    
"""
For Example:    input:   x = -121
               output:   False
"""
s = "mississippi"
p = "mis*is*p*."
                
solution = Solution()
result = solution.isMatch(s, p)
print('輸出爲:', result)    # False

參考

  1. https://www.bilibili.com/video/BV1Tt4y1U7QP
  2. https://leetcode-cn.com/problems/regular-expression-matching/solution/zheng-ze-biao-da-shi-pi-pei-dong-tai-gui-hua-by-jy/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章