❤leetcode,python2❤有效的括号

128 阅读1分钟

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        z = []
        for i in s:
            if i in ['(','[','{']:
                z.append(i)
            else:
                try:
                    eval(z[-1]+i)
                    del z[-1]
                except:
                    return False
        if len(z) != 0:
            return False
        else:
            return True