Determine whether a string of brackets is properly balanced and nested.
Valid Parentheses
You are given a string containing only bracket characters:
(, ), {, }, [ and ].
A string is valid if every opening bracket has a matching closing bracket of the same type, the pairs are closed in the correct order, and no closing bracket appears before its matching opening bracket.
Return true if the string is valid, otherwise return false.
A valid string may be empty.
Input Format
- A single string
sconsisting only of the characters(,),{,},[and].
Output Format
- Return a boolean value:
trueifsis valid, otherwisefalse.
Constraints
0 <= s.lengthscontains only bracket characters.- The answer should be determined in linear time with respect to the string length.
Example 1
Input
s = "()[]{}"Output
true
Explanation
Each opening bracket is matched by the same type of closing bracket in the correct order.
Example 2
Input
s = "(]"
Output
false
Explanation
The brackets are mismatched: ( must be closed by ), not ].
Show 1 more example
Example 3
Input
s = "([)]"
Output
false
Explanation
Although the counts look balanced, the nesting order is wrong.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.