678. Valid Parenthesis String

Description

image-20210908155643743

Solution

Using a list to store the availiable number of * scaned forward. If we meet a ‘)’ and there is no ‘(‘ in the stack, then we gonna use * to match.

As for mismatched ‘(‘, we should use * following to match it.

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
25
26
27
28
29
class Solution {
public:
bool checkValidString(string s) {
stack<int> stk;
vector<int> count(s.size()+1, 0);
for(int i = 0; i < s.size(); i++){
count[i+1] = count[i];
if(s[i] == '(')
stk.push(i);
else if(s[i] == '*')
count[i+1]+=1;
else{
if(stk.empty() && !count[i+1])
return false;
if(!stk.empty())
stk.pop();
else
count[i+1]-=1;
}
}
while(!stk.empty()){
auto top = stk.top(); stk.pop();
if(count[s.size()] - count[top + 1] <= 0)
return false;
count[s.size()]--;
}
return true;
}
};

image-20210908160331536