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.
An opening bracket: push it.
A closing bracket: the top must be its partner. Pop it.
How many brackets are open after each character of "([])"
1
02
11
20
3i
( opens. Push it. Stack: (
Move 1 of 4
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.
Closer on an empty stack: answer no.
Leftovers at the end: some bracket never closed: answer no.
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 stack