您的位置:首页 > 编程语言 > Python开发

DAY9:leetcode #20 Valid Parentheses

2016-07-22 16:15 495 查看
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.

Subscribe to see which companies asked this question

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
s_list = list(s)
sstack = []
for item in s_list:
if item in ['{','(','[']:
sstack.append(item)
else:
try:
if item == '}':
temp = sstack.pop()
if temp != '{':
return False
elif item == ')':
temp = sstack.pop()
if temp != '(':
return False
elif item == ']':
temp = sstack.pop()
if temp != '[':
return False
except Exception,e:
return False
if len(sstack) == 0:
return True
else:
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python