20. Valid Parentheses

20. Valid Parentheses

1. 題目

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

An input string is valid if:app

  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.ide

Example 1:code

Input: "()"
Output: true

Example 2:字符串

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

Example 3:input

Input: "(]"
Output: false

Example 4:string

Input: "([)]"
Output: false

Example 5:io

Input: "{[]}"
Output: true

2. 思路

本題是驗證給定的字符串,是否是有效的括號串。思路也很簡單,能夠用棧的方式實現。若是遇到了"[" ,"{" ,"("就入棧。若是遇到了"]" ,"}" ,")" 就出棧前一個字符,看前一個字符是否能匹配當前的字符。若是不行,則當前字符也入棧。最後程序結束的時候判斷棧裏面還有多少元素,若是是0則表明字符串是有效的括號串。class

3. 實現

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        if len(s) == 0 : return True

        for e in s :
            if len(stack) == 0 :
                stack.append(e)
                continue
            t = stack[-1]
            if ( t == "(" and e == ")" ) or ( t == "{" and e == "}" ) or ( t == "[" and e == "]" ):
                stack.pop(-1)
            else:
                stack.append(e)
        if len(stack) == 0 :return True
        return False
相關文章
相關標籤/搜索