Sunday, November 12, 2017

20. Valid Parentheses

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        new_string = ""
        left = "({["
        right = ")}]"
        for i in s:
            if i in left:
                new_string += i
            elif i in right:
                if len(new_string) == 0:
                    return False
                if right.index(i)!=left.index(new_string[-1]):
                    return False
                else:
                    new_string = new_string[:-1]                   
        return len(new_string) == 0

No comments:

Post a Comment