20. 有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
Given a string s 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.
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
提示:
- 1 <= s.length <= 104
- s 仅由括号 ‘()[]{}’ 组成
题解一(python):
class Solution:def isValid(self, s: str) -> bool:dic = {
')':'(',']':'[','}':'{'} # 字典stack = []for i in s:if stack and i in dic: # 若栈不为空且i为有效字符串if stack[-1] == dic[i]: # 若栈顶元素能和dic[i]匹配,则出栈stack.pop()else: return False # 否则就返回falseelse: stack.append(i) # 若i在栈中无,则压栈return not stack