leetcode 20. Valid Parentheses

来源:互联网 发布:鼻行动物存在吗 知乎 编辑:程序博客网 时间:2024/06/07 22:00

在学习数据结构中看到,因此回想起之前做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