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):
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 dic = {‘)‘:‘(‘,‘]‘:‘[‘,‘}‘:‘{‘} # 字典 4 stack = [] 5 for i in s: 6 if stack and i in dic: # 若栈不为空且i为有效字符串 7 if stack[-1] == dic[i]: # 若栈顶元素能和dic[i]匹配,则出栈 8 stack.pop() 9 else: 10 return False # 否则就返回false 11 else: 12 stack.append(i) # 若i在栈中无,则压栈 13 14 return not stack