Valid Parentheses
Given a string s made up only of the bracket characters ()[]{}, return true if the brackets are closed correctly, otherwise return false.
A string is valid when both of these conditions hold:
- Every opening bracket is closed by a closing bracket of the same type.
- Brackets are closed in the correct order, so every closing bracket matches the most recent unmatched opening bracket.
Examples
Input: "()"
Output: true
Input: "(]"
Output: false
Hints
Use a hash map that maps each closing bracket to its opening bracket so the match check is a constant-time lookup.
When you meet a closing bracket, return `false` immediately if the stack is empty or its top is not the matching opening bracket.
The stack holds only opening brackets that are still waiting to close, so its depth equals the current nesting depth and never exceeds `s.length`. A counter replaces the stack only when a single bracket type is allowed, and this input may mix `()`, `[]` and `{}`, so a stack is required.
Related Problems
Valid Parentheses
Given a string `s` made up only of the bracket characters `()[]{}`, return `true` if the brackets are closed correctly, otherwise return `false`.