Use a stack to ensure brackets close in the correct order.
Push opening brackets. For a closing bracket, check the top of the stack matches the corresponding opener; otherwise invalid.
The most recent unmatched opening bracket must be closed first (LIFO).
Use a stack to ensure brackets close in the correct order.
Push opening brackets. For a closing bracket, check the top of the stack matches the corresponding opener; otherwise invalid.
The most recent unmatched opening bracket must be closed first (LIFO).