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

Paintings of the English Channel coast 2

From yachting in Cowes, moving east along the Channel coast to end at the extreme eastern tip of Kent, with paintings from William Dyce, Walter Sickert, Paul Nash, William Holman Hunt, William Powell Frith and others.

via The Eclectic Light Company

Concurrent Servers: Part 8 - Go

This is part 8 in a series of posts on writing concurrent network servers. In this part, we'll switch to Go and see how it tackles the challenges described earlier in the series. All posts in the series: Part 1 - Introduction Part 2 - Threads Part 3 - Event-driven Part 4 - libuv Part 5 - Redis case ...

via Eli Bendersky

You should never be angry at work

I try not to give a lot of prescriptive advice about working in tech companies1. There are many ways to be successful, and every company works differently. If you’re shipping projects and your management chain is happy, it doesn’t really matter how you’ve accomplished it. However, there’s one thing ...

via Sean Goedecke