leetcode 20. Valid Parentheses

来源:互联网 发布:万花成女捏脸数据 编辑:程序博客网 时间:2024/05/22 08:19

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 == []