Saltar a contenido

20. Valid Parentheses

20
Valid Parentheses Easy
Tags: Stack, String

Solución (Python)

class Solution(object):
    def isValid(self, s):
        stack = []
        closeToOpen = { ")": "(", "]" : "[",  "}" : "{" }

        for c in s:
            if c in closeToOpen:   # 'in' porque queremos saber si c esa en sus yaves
                if stack and stack[-1] == closeToOpen[c]:
                    stack.pop()
                else:
                    return False
            else:
                stack.append(c)
        return True if not stack else False

sol = Solution()
print(sol.isValid("()"))
print(sol.isValid("()[]{}"))
print(sol.isValid("(]"))
print(sol.isValid("([])"))
print(sol.isValid("([)]"))