Valid Parentheses
Problem statement
Given a string s that contains only the characters (, ), [, ], { and }, decide whether it is valid.
The string is valid when all of these rules hold:
- Every opening bracket is closed by a closing bracket of the same type.
- Brackets are closed in the right order: the bracket opened last is closed first.
- Every closing bracket matches an opening bracket that comes before it.
Return true if s is valid, and false otherwise.
Function
isValid(s: String) → booleanExamples
Example 1
s = "()[]{}"return = trueEach opening bracket is closed right away by a bracket of the same type.
Example 2
s = "{[()]}"return = trueThe brackets are nested. The last bracket opened, (, is closed first, then [, then {.
Example 3
s = "([)]"return = falseThe [ was opened after the (, so it must be closed first. The next closing bracket is ) while [ is still open, so the order is wrong.
Example 4
s = "(("return = falseTwo brackets are opened but neither is closed.
Constraints
1 <= s.length <= 10^4scontains only the characters()[]{}.