20. Valid Parentheses

20. Valid Parentheses

題目:

https://leetcode.com/problems/valid-parentheses/

難度:

Easy

雖然知道肯定是用stack來解決,但是我是看了hint才自己解答的,因為可能想復雜了。

因為一共只有三種狀況"(" -> ")", "[" -> "]", "{" -> "}".

一遇到左括號就入棧,右括號出棧,這樣來尋找對應

需要檢查幾件事:

  • 右括號時stack里還有沒有東西
  • 出stack的是否對應
  • 最終stack是否為空
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        leftP = "([{"
        rightP = ")]}"
        
        stack = []
        for char in s:
            if char in leftP:
                stack.append(char)
            elif char in rightP:
                if stack == []:
                    return False
                item = stack.pop()
                if char == "]" and item != "[":
                    return False
                elif char == ")" and item != "(":
                    return False
                elif char == "}" and item != "{":
                    return False
        return stack == []
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容