Valid Parentheses
Problem statement
The string s is built from three kinds of brackets: round ( ), square [ ] and curly { }.
Call s well formed if you can split all of its characters into pairs such that:
- each pair is an opening bracket and, somewhere to its right, a closer of the same kind, and
- pairs never cross: between the two brackets of any pair, every other bracket has its partner there too.
Report whether s is well formed: true if it is, false if it is not.
Function
isValid(s: String) → booleanExamples
Example 1
s = "{[()()]}"return = trueThe two () pairs close inside [ ], which closes inside { }. Every bracket is closed by the same type, in the right order. The answer is true.
Example 2
s = "{(})"return = falseAfter {(, the most recent open bracket is (, so the next closer must be ). It is } instead. The answer is false.
Example 3
s = "(()[]"return = falseThe inner () and [] pairs match, but the first ( is never closed. The answer is false.
Constraints
shas at least1and at most10^4characters.- Only the six bracket characters
()[]{}appear ins.