Valid Parentheses
EasyStack · Microsoft
You are given a string s that contains only the bracket characters (, ), [, ], {, and }.
Return True if the brackets are valid and False otherwise. The string is valid when:
- every opening bracket is closed by a closing bracket of the same type,
- brackets close in the correct order, so the most recently opened bracket that is still open must be closed first, and
- every closing bracket has a matching opening bracket before it.
Example 1
- Input:
- s = "{[()]}[]"
- Output:
- True
- Explanation
- Each bracket is closed by its own type, innermost first:
()inside[]inside{}, followed by a separate[]pair.
Example 2
- Input:
- s = "[(])"
- Output:
- False
- Explanation
- The counts match, but
]arrives while(is the most recently opened bracket, so the nesting is wrong.
Example 3
- Input:
- s = "(()"
- Output:
- False
- Explanation
- One
(is never closed.
Constraints
- 1 ≤
s.length≤ 104 scontains only the characters()[]{}