Valid Parentheses

Problem

Given a string s containing just the characters ’(’, ’)’, ’{’, ’}’, ’[’ and ’]’, determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only ’()[]{}’.

Solution

A classic stack problem.

class Solution {
    Stack<Character> st = new Stack<Character>();

    public boolean isValid(String s) {
        for (var c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                st.push(c);
            } else {
                if (st.isEmpty()) {
                    return false;
                }
                var t = st.pop();
                if (c == ')' && t != '(') {
                    return false;
                } else if (c == ']' && t != '[') {
                    return false;
                } else if (c == '}' && t != '{') {
                    return false;
                }
            }
        }
        return st.isEmpty();
    }
}

Recent posts from blogs that I like

Watching o3 guess a photo's location is surreal, dystopian and wildly entertaining

via Simon Willison

Pre-Raphaelite landscapes of John Brett: 1 Travels

A relatively latecomer, he started painting Pre-Raphaelite landscapes in 1856, with stunning results in the Alps, and his monumental view of Florence, but those proved unsuccessful.

via The Eclectic Light Company

Sometimes the reason you can’t find people you resonate with is because you misread the ones you meet

Sometimes two people will stand next to each other for fifteen years, both feeling out of place and alone, like no one gets them, and then one day, they look up at each other and say, “Oh, there you are.”

via Henrik Karlsson