Valid Parentheses
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.
解题方法是:
一个个检查给的characters,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。
全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for item in s:
if item in dict.values():
stack.append(item)
elif item in dict.keys():
if len(stack) == 0 or dict[item] != stack.pop():
return False
return len(stack) == 0
注意 :if len(stack) == 0 or dict[item] != stack.pop()中or前后的顺序,需要先判断len(stack)是否等于0,如果len(stack) == 0,则return false;如果len(stack) != 0,则再去判断or后面的条件。如果写成 dict[item] != stack.pop() or len(stack) == 0,那么如果输入是 ‘ ]’,返回错误信息:pop from empty list。所以这道题,我们需要先判断len(stack)是否等于0,然后再pop
Last updated
Was this helpful?