Valid Parentheses

来源:互联网 发布:中科院力学研究所知乎 编辑:程序博客网 时间:2024/06/03 03:50

题目:

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):
        """
        :type s: str
        :rtype: bool
        """
        map = {'(':')', '{':'}', '[':']'}
        res = []
        for i in s:
            if i=='(' or i=='{' or i=='[':
                res.append(i)
            elif len(res)!=0 and i==map[res[-1]]:
                res.pop()
            else:
                return False
        return len(res)==0

0 0
原创粉丝点击