Paths Subjects Questions Quizzes Pricing Search
Beginner Open Pro

Valid Parenthesis Expression

Given a string s that consists only of the bracket characters (, ), [, ], {, and }, determine whether the string is a valid bracket expression.

A string is valid if:

  1. Every opening bracket has a matching closing bracket of the same type.
  2. Opening brackets are closed in the correct order (the most recently opened bracket must be the next one closed).
  3. Every closing bracket has a corresponding opening bracket earlier in the string.

Return true if the string is valid, false otherwise.

Example 1

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

Example 2

Input: s = "([)]"
Output: false
Explanation: The "]" closes before the "[" that opened after it,
and the "(" is closed by ")" out of order.

Example 3

Input: s = "{[]}"
Output: true

Constraints

  • 0 <= s.length <= 10^4
  • s consists only of the characters ()[]{}.

Share this question

← Back to Stacks practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.