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
本文介绍了一种使用栈数据结构来验证括号字符串的有效性的方法。该方法通过遍历输入字符串并利用栈进行开闭括号的匹配来实现,确保括号成对出现且顺序正确。
908

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



