Valid Parentheses

EasyStack

A string s contains only the characters (, ), [, ], { and }.

It is valid when every opening bracket is closed by a bracket of the same kind, the brackets close in the right order, and no closing bracket comes without an opening one. Return true if s is valid.

Examples

Example 1
Input:  s = "{[()]}"
Output: true

Each pair closes inside the pair around it.

Example 2
Input:  s = "([)]"
Output: false

The [ is still open when ) tries to close the (.

Constraints

  • 1 ≤ s.length ≤ 10⁴

Stuck?

Hint 1

Push each opening bracket onto a stack.

Hint 2

A closing bracket must match the bracket on top of the stack. At the end, the stack must be empty.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur