Valid Parenthesis String Problem


Description

LeetCode Problem 678.

Given a string s containing only three types of characters: ‘(‘, ‘)’ and ‘*’, return true if s is valid.

The following rules define a valid string:

  • Any left parenthesis ‘(‘ must have a corresponding right parenthesis ‘)’.
  • Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(‘.
  • Left parenthesis ‘(‘ must go before the corresponding right parenthesis ‘)’.
  • ’*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(‘ or an empty string “”.

Example 1:

1
2
Input: s = "()"
Output: true

Example 2:

1
2
Input: s = "(*)"
Output: true

Example 3:

1
2
Input: s = "(*))"
Output: true

Constraints:

  • 1 <= s.length <= 100
  • s[i] is ‘(‘, ‘)’ or ‘*’.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    bool checkValidString(string s) {
        int lower = 0, upper = 0;
        for (char c : s) {
            if (c == '(') {
                lower ++;
                upper ++;
            } else if (c == ')') {
                lower --;               
                upper --;
            } else { 
                // * encountered
                lower --;
                upper ++;
            }
            lower = max(lower, 0);
            if (upper < 0) 
                // unmatched ')' found in the middle of string
                return false;
        }
        return lower == 0;
    }
};




Related Posts

Validate Stack Sequences Problem

LeetCode 946. Given two integer arrays pushed and popped each...

Stamping The Sequence Problem

LeetCode 936. You are given two strings stamp and target....

Score Of Parentheses Problem

LeetCode 856. Given a balanced parentheses string s, return the...

Minimum Add To Make Parentheses Valid Problem

LeetCode 921. A parentheses string is valid if and only...

Maximum Width Ramp Problem

LeetCode 962. A ramp in an integer array nums is...

Decoded String At Index Problem

LeetCode 880. You are given an encoded string s. To...