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 Stack:#定义栈 后进先出
data=[]
def push(self,item):
self.data.append(item)
def pop(self):
if self.data == []:
return False
else:
return self.data.pop()
def length(self):
return len(self.data)
def clear(self):
self.data=[]
class Solution:
# @return a boolean
def isValid(self, s):
p={'(':')','[':']','{':'}'}
stack=Stack()
stack.clear()
for c in s:
if c in p.keys():
stack.push(c)
elif c in p.values():
k=stack.pop()
if k==False or p[k]!=c:
return False
else:
return False
if stack.length() == 0:
return True
else:
return Falseleetcode_num20_Valid Parentheses
原文:http://blog.csdn.net/eliza1130/article/details/44062421