BackmediumStack Amazon

Valid Parentheses String Solution

Problem Statement

Given a string `s` containing only the characters '(', ')', and '*', determine if the string is valid. A string is valid if and only if: 1. Any left parenthesis '(' must have a corresponding right parenthesis ')'. 2. Any right parenthesis ')' must have a corresponding left parenthesis '('. 3. Left parenthesis '(' must go before the corresponding right parenthesis ')'. 4. '*' can be treated as a single right parenthesis ')', a single left parenthesis '(', or an empty string "".

Example 1
Input
()
Output
true

Explanation: The string is valid. The '(' has a matching ')' and they appear in the correct order.

Example 2
Input
(*)
Output
true

Explanation: The '*' can be treated as an empty string, making the string '()', which is valid.

Example 3
Input
(*))
Output
true

Explanation: The first '*' can be treated as '(', making the string '(())', which is valid. Alternatively, the first '*' can be an empty string, and the second ')' matches the '('. So the string becomes '()', which is valid.

Example 4
Input
)(
Output
true

Explanation: The ')' appears before the '(', violating the order rule.

Constraints

  • 1 <= s.length <= 100
  • s[i] is either '(', ')', or '*'.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free