Given a string containing only ‘(‘,’) ‘, ‘{‘,’} ‘, ‘[‘,’] ‘, check whether the string is valid.

A valid string must meet the following requirements:

An open parenthesis must be closed with a close parenthesis of the same type. The left parentheses must be closed in the correct order. Note that an empty string can be considered a valid string.

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
Copy the code