Valid Parentheses
Check that every bracket in a string is closed by the right type of bracket, in the right order.
Given a string struefalse
Example 1
Output: true
Example 2
Output: true
Example 3
Output: false
Explanation: '(' is closed by the wrong type of bracket.
Example 4
Output: false
Explanation: there is one of each bracket, but '(' closes before '[', which was opened after it.
The Idea
You have probably written brackets inside brackets, in arithmetic such as 2 Ć (3 + [4 ā 1]) or in Java, where a method's braces sit inside a class's braces. Each pair wraps a part of the text, and an inner pair must end before the outer one does, like a small box inside a bigger box.
Example 4, "([)]""([])"
It must match the most recent opening bracket that is still open. Read the string from left to right and keep the open brackets in a pile, putting each new one on top. A closing bracket must match the bracket on top, which is then closed and comes off the pile. Look at the picture below.
In the top row, "([])""([)]"
A pile where you only add to the top and only take from the top is called a stack. The last bracket put on comes off first, which is exactly the order in which brackets must close.
Solution Approach
Turning the pile into code means settling three things: which Java class holds the stack, what goes on it, and the ways a string can fail. First, though, a slower method without a stack shows what the stack saves.
Removing pairs one round at a time
Is a stack really needed? A valid string that is not empty always has a matched pair side by side somewhere, such as "()" or "[]". Delete every such pair, and what is left must still be valid. Repeat until nothing changes, and the string was valid if nothing is left.
This works, but each round scans the whole string, and a deeply nested string loses only one pair per round. "((((()))))"
Holding the stack in Java
Which class should hold the stack? Java has an old class named StackDequeDequeArrayDequepushpopisEmpty
What goes on the stack
Should the stack hold the opening brackets themselves, as the picture does? It can, but then each closing bracket needs a lookup to find which opening bracket it belongs to. It is simpler to push the closing bracket that each opener is waiting for: ) for (, ] for [ and } for {. A closing bracket is then correct exactly when it equals the character on top.
Three ways to fail
When is the answer false")""(]""([)]""((("
Java Solution
The method isValid
- First, create an empty stack named
, anexpected of characters. It holds the closing brackets the string still owes.ArrayDeque - Loop over the characters of
, one characters at a time, and choose what to do with ac onswitch .c - For an opening bracket, push its closing partner onto
: ) for (, ] for [ and } for {.expected - Any other character is a closing bracket and goes to the
branch. Ifdefault is empty, or the bracket popped from its top differs fromexpected , returnc at once.false - After the loop, return
, which isexpected.isEmpty() only if every opening bracket was closed.true
The main"([])""{[()]}""(((""())"
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParentheses {
public static boolean isValid(String s) {
Deque<Character> expected = new ArrayDeque<>(); // closing brackets we still need
for (char c : s.toCharArray()) {
switch (c) {
case '(' -> expected.push(')');
case '[' -> expected.push(']');
case '{' -> expected.push('}');
default -> { // a closing bracket
if (expected.isEmpty() || expected.pop() != c) {
return false; // nothing open, or the wrong one
}
}
}
}
return expected.isEmpty(); // every opening bracket was closed
}
public static void main(String[] args) {
String[] tests = {"()", "()[]{}", "(]", "([)]", "([])", "{[()]}", "", "(((", "())"};
for (String s : tests) {
System.out.println("\"" + s + "\" -> " + isValid(s));
}
}
}
Running it prints:
"()" -> true
"()[]{}" -> true
"(]" -> false
"([)]" -> false
"([])" -> true
"{[()]}" -> true
"" -> true
"(((" -> false
"())" -> false
Compare "([)]" -> false"([])" -> true"{[()]}"trueexpected
The last two lines fail in the ways the examples do not show. "((("expected.isEmpty()truetrue"(((""())"expectedfalse
The original implementation,
Complexity
The method reads the string once and keeps one stack.
- Time: O(n), because each of the n characters is read once and costs either one push, or one pop and one comparison.
- Space: O(n), because the stack holds one closing bracket for each opening bracket not yet closed, and a string such as
keeps all of its n characters open at once."(((("
With only one type of bracket, a count of the open brackets can replace the stack, as in