Description
Given a string containing only three types of characters: ‘(’, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:
- 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.
- An empty string is also valid.
Example 1:
Input: "()"
Output: True
Example 2:
Input: "(*)"
Output: True
Example 3:
Input: "(*))"
Output: True
Note:
The string size will be in the range [1, 100].
Solution
class Solution {
public boolean checkValidString(String s) {
int cmin = 0, cmax = 0; // open parenthesis openCount in range [cmin, cmax]
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
cmax++;
cmin++;
}
else if (s.charAt(i) == ')') {
cmax--;
cmin--;
}
else {
cmax++; // if '*' become '('
cmin--; // if '*' become ')'
// if '*' become '*', nothing happend
// openCount will be in range [cmin-1, cmax+1]
}
// do not have enough open parenthesis to match close parenthesis -> invalid
if (cmax < 0) return false;
// it's invalid state that open parenthesis count < 0, it cannot be negative
cmin = Math.max(cmin, 0);
}
// if cmin != 0, means that there are open parenthesis left
// if cmin == 0, means we can found openCount == 0 in range [cmin, cmax]
return cmin == 0;
}
}