Brackets that match
The newest open bracket must close first. About 10 minutes.
The newest open bracket closes first
In the text {[()]}, the round bracket opened last, so it must close first. Then the square one closes, then the curly one. Like nesting boxes inside each other, the last one opened is the first one closed: last in, first out.
So keep the open brackets on a stack.
( opens. Push it. Stack: (
Three ways to fail
A closer arrives and the stack is empty: there is nothing for it to close. A closer arrives and the top is a different kind, as in a round bracket closed by a square one. Or the text ends with open brackets still waiting on the stack.
To look at the top without taking it, use the last item of the list in Python, top in C++, peek in Java, or the last index in JavaScript.
partner = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif not stack:
return False
elif stack.pop() != partner[ch]:
return False
return not stackReading from the left, at which character do you first know the string is unbalanced?
s = "[(]"
- AThe ] at index 2
- BThe ( at index 1
- CIt's balanced
Show the answer
The ] at index 2. The top of the stack is (, but ] needs a [. That's a mismatch.
Balanced brackets
s has only the brackets ( ) [ ] { }. It's balanced when every opening bracket is closed by one of the same kind, and the most recently opened bracket is always the next to close. Return true if s is balanced. An empty string is balanced.
s = "{[()]}()" → true0 ≤ length of s ≤ 100,000 · s has only ( ) [ ] { }