给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
例子:输入:s = "()[]{}"
输出:true
括号有效,左括号必须有的对应的右括号
括号匹配是栈解决的经典问题
字符串无效的2种情况
1 遍历字符串左括号多或者没有匹配的右括号
2 遍历字符串右括号没有对应的左括号
1 仅使用栈
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# 括号有效,左括号必须有的对应的右括号
# 括号匹配是栈解决的经典问题
# 字符串无效的三种情况
# 1 遍历字符串左括号没有对应的右括号 左括号多或者没有匹配的右括号
# 2 遍历字符串右括号没有对应的左括号
# 仅使用栈
stack = []
for x in s:
if x == '(':
stack.append(')')
elif x == '{':
stack.append('}')
elif x == '[':
stack.append(']')
# stack是要pop的,当遍历完字符串时栈已经空了,说明右多了
# 遍历的过程发现栈顶的元素与当前元素不等,则说明左没有对应的右
elif not stack or stack[-1] != x:
return False
else:
stack.pop()
# 遍历完字符串发现栈不为空,说明左多
# 遍历完字符串栈为空,为True
return True if not stack else False
2 使用栈和字典
class Solution:
def isValid(self, s: str) -> bool:
# 使用字典和栈
stack = []
mapping = {
'(' : ')',
'[' : ']',
'{' : '}'
}
for item in s:
if item in mapping.keys():
stack.append(mapping[item])
# 当遍历字符串时stack为空,右括号多
# 当遍历时 当前元素与栈顶元素不同时
elif not stack or item != stack[-1]:
return False
else:
stack.pop()
# 当遍历完字符串后 栈不为空
return True if not stack else False