20. Valid Parentheses

20. Valid Parentheses

[Easy] “Given a string containing just the characters ‘(', ‘)', ‘{', ‘}', ‘[’ and ‘]', determine if the input string is valid, i.e. open brackets must be closed by the same type of brackets; open brackets must be closed in the correct order; an empty string is considered valid."

Link to Leetcode

Note: old solution, should review (TODO:)

Python3:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        valid = {
            '(': ')', 
            '{': '}', 
            '[': ']'
        }
        
        if len(s) == 1:
            return False
        
        for c in s:
            if c in valid.values():
                if len(stack) == 0:
                    return False
                else:
                    last = stack.pop()
                    if (last in valid.keys()) and (valid[last] != c):
                        return False
            else:
                stack.append(c)
        
        if len(stack) > 0:
            return False
        else:
            return True