☰ All problems

2. Valid Parentheses

EasyStringStack

Given a string s made only of the characters ()[]{}, decide whether it is valid:

  • every opening bracket is closed by a bracket of the same type,
  • brackets close in the correct order,
  • every closing bracket has a matching opening bracket.
Example 1
Input: s = "()"
Output: true
Example 2
Input: s = "()[]{}"
Output: true
Example 3
Input: s = "(]"
Output: false
Example 4
Input: s = "([)]"
Output: false

Explanation: The brackets are matched in count but closed in the wrong order.

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of ()[]{}
💡 Hint 1

The most recently opened bracket must be the first one closed. Which data structure is last-in, first-out?

💡 Hint 2

At the end, anything still open means the string is invalid.

/**
 * @param {string} s
 * @return {boolean}
 */
function isValid(s) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc