在学习数据结构中看到栈,因此回想起之前做leetcode时遇到的一题:
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(object):
def isValid(self, s):
mystack = []
for item in s:
if item in ["(","[","{"]:
mystack.append(item)
if item in [")","]","}"]:
if mystack == []:
return False
top = mystack[-1]
if (top == '(' and item == ')') or (top == "[" and item == "]") or (top == "{" and item == "}"):
mystack.pop()
else:
return False
return len(mystack) == 0