Data Structures & Algorithms View on GitHub โ†—

Validate Parentheses

Java

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');

        for (char c : s.toCharArray()) {
            if (!map.containsKey(c))
                stack.push(c);

            else {
                if (!stack.isEmpty()) {
                    if (stack.peek() != map.get(c))
                        return false;
                    stack.pop();
                } else {
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }
}

Python

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        parenthDict = {"}": "{", ")": "(", "]": "["}

        for c in s:
            if c in parenthDict:
                if stack and stack[-1] == parenthDict[c]:
                    stack.pop()
                else:
                    return False
            else:
                stack.append(c)

        return True if not stack else False

Enjoyed this solution?

I write about software engineering, algorithms, and lessons learned. Check out more in the newsletter.

Browse the newsletter