Video in progress
Write a function that checks whether a sequence of brackets is correctly closed: "([]{})" is valid, "(]" is not.
I push opening brackets onto a stack, and when a closing bracket arrives I check that it matches the top of the stack. At the end the stack must be empty. Time is O(n), memory is O(n) in the worst case.
📖 Answer
static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
switch (c) {
case '(' -> stack.push(')');
case '[' -> stack.push(']');
case '{' -> stack.push('}');
default -> {
if (stack.isEmpty() || stack.pop() != c) return false;
}
}
}
return stack.isEmpty();
}
A small trick: instead of the opening bracket, we push the matching closing one. Then the comparison is a single !=, and no separate Map is needed.
Two cases that are usually forgotten:
")(": when a closing bracket arrives the stack is empty, so we checkisEmpty()first to keeppop()from throwing an exception;"((": the loop finishes but the stack still has items. That's why the end isstack.isEmpty(), notreturn true.
If there is only one type of bracket, you don't even need a stack: a single counter is enough.
Sign up to mark studied questions and save your progress.