题目原文:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
题目大意:
给出一个括号字符串,判断括号是否正确匹配。
题目分析:
本题考查堆栈的使用,遇到左边的括号全部入栈,遇到右边的括号则看栈顶的括号是不是对应的左括号,如是则弹出,如不是则返回错误。如果整个括号字符串扫完之后栈恰好为空,则是合法匹配。
源码:(language:python)
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
for c in s:
if c in ['(','[','{']:
stack.append(c)
else:
if(len(stack)==0):
return False
top=stack[len(stack)-1]
if ((c == ')' and top=='(') or (c == ']' and top=='[') or (c == '}' and top == '{')):
stack.pop()
else:
return False
return len(stack)==0
成绩:
43ms,beats 55.57%,众数40ms,27.91%
本文介绍了一个使用堆栈数据结构来检查括号是否正确配对的算法。通过遍历字符串并利用堆栈记录左括号,当遇到右括号时检查其是否与堆栈顶部的左括号相匹配。
662

被折叠的 条评论
为什么被折叠?



