您的位置:首页 > 其它

leetcode_num20_Valid Parentheses

2015-03-04 16:57 204 查看
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 False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: