文章目录
题目
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([])"
输出:true
题解
使用栈
python
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# 栈: "(", "{", "[", ")", "}", "]"
stack = []
mapping = {
'(': ')',
'[': ']',
'{': '}'
}
for item in s:
if item in mapping.keys():
stack.append(mapping[item])
# 按照顺序读取的,使用 if not stack 来判断栈是否为空
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False