Problem:
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.
Idea:
Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return False.
Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return True, else return False.
Solution:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = list()
for item in s:
if item == '(' or item == '{' or item == '[' :
l.append(item)
elif item == ')':
if len(l) == 0:
return False
elif l[len(l)-1] == '(':
l.pop()
else:
return False
elif item == '}':
if len(l) == 0:
return False
elif l[len(l)-1] == '{':
l.pop()
else:
return False
elif item == ']':
if len(l) == 0:
return False
elif l[len(l)-1] == '[':
l.pop()
else:
return False
if len(l) == 0:
return True
else:
return False
括号匹配验证

本文介绍了一种使用栈解决括号匹配问题的有效算法。通过遍历输入字符串中的括号,算法能够判断括号是否正确配对及闭合。适用于只包含'(){}
269

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



