678 Valid Parenthesis String
1. Question
Input: "()"
Output: TrueInput: "(*)"
Output: TrueInput: "(*))"
Output: True2. Implementation
3. Time & Space Complexity
Last updated
Input: "()"
Output: TrueInput: "(*)"
Output: TrueInput: "(*))"
Output: TrueLast updated
class Solution {
public boolean checkValidString(String s) {
return check(s, 0, 0);
}
public boolean check(String s, int pos, int count) {
if (pos == s.length()) {
return count == 0;
}
if (count < 0) {
return false;
}
if (s.charAt(pos) == '(') {
return check(s, pos + 1, count + 1);
}
else if (s.charAt(pos) == ')') {
return check(s, pos + 1, count - 1);
}
// check all possible cases when current character is "*"
else {
return check(s, pos + 1, count + 1) || check(s, pos + 1, count - 1) || check(s, pos + 1, count);
}
}
}class Solution {
public boolean checkValidString(String s) {
int low = 0, high = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
++low;
++high;
}
else if (c == ')') {
if (low > 0) {
--low;
}
--high;
}
else {
if (low > 0) {
--low;
}
++high;
}
if (high < 0) {
return false;
}
}
return low == 0;
}
}