【leetcode】20. Valid Parentheses

一、题目描述(最长公共前缀)

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

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.

给定一个只包含字符'(',')','{','}','[',']'的字符串,确定输入字符串是否有效。
如果输入字符串有效:
1.必须使用相同类型的括号关闭左括号。
2.必须以正确的顺序关闭左括号。
请注意,空字符串也被视为有效。

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

二、题目分析

括号的匹配问题,考虑数据结构使用栈,后进先出,如果栈为空或者括号和当前栈顶符号不匹配,就入栈,如果右括号和当前栈顶符号匹配,就弹出栈顶元素

注意:要满足查询的字符串在字典中(是左括号),不然会报错······

三、代码实现

class Solution:
    def isValid(self,s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        dict = {'(': ')', '{': '}', '[': ']'}
        for i in range(len(s)):
            if len(stack) == 0:
                stack.append(s[i])
            elif stack[-1] in dict and dict[stack[-1]] == s[i]:
                #要满足查询的字符串在字典中,不然会报错········
                stack.pop()
            else:
                stack.append(s[i])
        return stack == []

猜你喜欢

转载自blog.csdn.net/jinjinjin2014/article/details/80945063