Why it works
- Pairs cannot cross, so the bracket a closer must match is always the newest one still open: the top of the stack. Pushing the closer it waits for turns the check into one comparison.
- A matched pair is popped at once, so whatever was nested inside is gone before the outer closer arrives, and the outer opener is on top again.
- Two ways to fail need their own checks: a closer with nothing expected, and an opener still waiting when the string ends. That is why the last line asks whether the stack is empty.
Complexity
Time O(n): each bracket is pushed or popped once. Memory O(n): a string of only openers puts all of them on the stack.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗