题目原文:
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%