Valid Parentheses
Problem statement
Given a string s made only of brackets, return true if it is balanced and false otherwise.
A string is balanced when:
- every closing bracket closes the most recent opening bracket that is still open, and it is the same kind (
)closes(,]closes[,}closes{); - no closing bracket appears when nothing is open; and
- every opening bracket is closed by the end.
Function
isValid(s: String) → booleanExamples
Example 1
s = "{[()]}()"return = trueThe ( inside is closed first, then [, then {, each by its own kind of bracket. The last pair () is closed right away. Every opener is closed in the right order, so the answer is true.
Example 2
s = "([)]"return = falseAfter ( and [ are opened, the next character is ). The most recent unclosed opener is [, not (, so the string is not balanced, even though each kind appears once as opener and once as closer.
Example 3
s = "(("return = falseTwo openers are never closed, so the answer is false.
Constraints
1 <= s.length <= 10^4sconsists only of the characters(,),[,],{, and}.