leetcode: 20. Valid Parentheses

来源:互联网 发布:sql注入入门 编辑:程序博客网 时间:2024/05/21 06:34

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.

AC

class Solution():    def isValid(self, x):        d, lst = {"(":")", "[":"]", "{":"}"}, []        for ele in x:            if ele in d.keys():   # prefix: push                lst.append(ele)            elif not (lst and d[lst.pop()] == ele):    # suffix: pop, then if cannot match, return False                return False        return len(lst) == 0if __name__ == "__main__":    assert Solution().isValid("()[]{}") == True    assert Solution().isValid("()[{]}") == False    assert Solution().isValid("[") == False    assert Solution().isValid("]") == False