1. 程式人生 > >LeetCode20:Valid Parentheses

LeetCode20:Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

LeetCode:連結

用棧來操作,將所有的字元依次入棧,當棧頂的括號和正要入棧的括號匹配時將棧頂的括號彈出且不入棧,否則入棧新的括號。最後,只有當棧裡沒有括號時,才表明輸入是有效的。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        necessary = ["()", "[]", "{}"]
        stack = []
        for i in range(len(s)):
            stack.append(s[i])
            '''必須是stack[-2] + stack[-1]這個順序'''
            if len(stack) >= 2 and stack[-2] + stack[-1] in necessary:
                stack.pop()
                stack.pop()
        return len(stack) == 0