Valid Parentheses

Problem Id: 20 Difficulty: Easy Tag: String Tag: Stack


Intuition

Use a stack.

Solution


class Solution:
    MAPPING = {
        '}': '{',
        ')': '(',
        ']': '['
    }

    def isValid(self, s: str) -> bool:
        stack = []
        for c in s:
            if c in '({[':
                stack.append(c)
            elif c in ')}]':
                if len(stack) == 0:
                    return False
                if stack.pop() != self.MAPPING[c]:
                    return False
        return len(stack) == 0