一、题目描述(最长公共前缀)
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:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
给定一个只包含字符'(',')','{','}','[',']'的字符串,确定输入字符串是否有效。
如果输入字符串有效:
1.必须使用相同类型的括号关闭左括号。
2.必须以正确的顺序关闭左括号。
请注意,空字符串也被视为有效。Example 1:
Input: "()" Output: trueExample 2:
Input: "()[]{}" Output: trueExample 3:
Input: "(]" Output: falseExample 4:
Input: "([)]" Output: falseExample 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 == []