LeetCode_Everyday:020 Valid Parentheses

LeetCode_Everyday:020 Valid Parentheses


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

題目:

給定一個只包括'(',')','{','}','[',']'的字符串,判斷字符串是否有效。

有效字符串需滿足:

1. 左括號必須用相同類型的右括號閉合。
2. 左括號必須以正確的順序閉合。

注意空字符串可被認爲是有效字符串。

示例:

  • 示例 1:
    輸入: "()"
    輸出: true
    
  • 示例 2:
    輸入: "()[]{}"
    輸出: true
    
  • 示例 3:
    輸入: "(]"
    輸出: false
    
  • 示例 4:
    輸入: "([)]"
    輸出: false
    
  • 示例 5:
    輸入: "{[]}"
    輸出: true
    

代碼

方法一: 堆棧 題解

執行用時:32 ms, 在所有 Python3 提交中擊敗了97.36%的用戶
內存消耗:13.8 MB, 在所有 Python3 提交中擊敗了5.22%的用戶

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {')':'(',']':'[','}':'{'}
        stack = []
        for i in s:
            if stack and i in dic:
                if stack[-1] == dic[i]: stack.pop()
                else: return False
            else: stack.append(i)
            
        return not stack

"""
For Example:    input:    s = "{[]}"
               output:    true
"""
s = "{[]}"
                
solution = Solution()
result = solution.isValid(s)
print('輸出爲:', result)

參考

  1. https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/

此外

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

在這裏插入圖片描述

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