您的位置:首页 > 理论基础 > 数据结构算法

leetcode 20. Valid Parentheses

2017-10-13 17:18 513 查看
在学习数据结构中看到,因此回想起之前做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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息