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.
需要注意,出栈的时候需判断是否为空。
class Solution:
# @return a boolean
def isValid(self, s):
stack=[]
left=('(','{','[')
right=(')','}',']')
dic={
"(":")",
"[":"]",
"{":"}",
}
for x in s:
if x in left:
stack.append(x)
elif x in right:
<span style="color:#ff0000;">if stack==[]:
return False</span>
tmp=stack.pop()
if dic[tmp]!=x:
return False
else:
return False
if stack==[]:
return True
return False