您的位置:首页 > 其它

leetcode 20. Valid Parentheses

2017-11-18 10:49 471 查看
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.

思路:创建一个栈来存放各种括号的左边部分,一个字典来存放每种括号配对。遍历整个字符串,每次先判断是否为左边部分:

(1)是,存入stack

(2)不是,判断是否stack为空,空的话就说明前面没有与这个右边部分匹配的,若不为空,还要判断是否与stack最后加入的字符配对

最后返回stack是否为空。

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