您的位置:首页 > 其它

[Leetcode] 20. Valid Parentheses

2017-02-20 12:00 429 查看
Problem:

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.

Idea:

Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return
False
.

Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return
True
, else return
False
.

Solution:

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