天天看點

有效的括号題目解答思路python 代碼

有效的括号

  • 題目
  • 解答思路
  • python 代碼

題目位址

題目

給定一個隻包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字元串,判斷字元串是否有效。

有效字元串需滿足:

左括号必須用相同類型的右括号閉合。

左括号必須以正确的順序閉合。

注意空字元串可被認為是有效字元串。

示例 1:

輸入: "()"
輸出: true
           

示例 2:

輸入: "()[]{}"
輸出: true
           

示例 3:

輸入: "(]"
輸出: false
           

示例 4:

輸入: "([)]"
輸出: false
           

示例 5:

輸入: "{[]}"
輸出: true
           

解答思路

  1. 用棧, 左括号就插入, 右括号就取出配對. 失敗就傳回F.
  2. 最終,周遊完字元串之後, 棧是空的,return True.

python 代碼

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        parenttheses = {')': '(', '}': '{', ']': '['}

        for i in s:
            if i not in parenttheses:
                stack.append(i)
            elif stack and stack.pop() == parenttheses[i]:
                continue
            else:
                return False
        return not stack
           

繼續閱讀