[LeetCode] Valid Parenthesis String

678. Valid Parenthesis String

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:

  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. ‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(‘ or an empty string.
  5. An empty string is also valid.
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
30
31
32
33
34
35
class Solution {
public:
bool checkValidString(string s) {
list<char> myList;
auto iterator = myList.rbegin();
for(int i = 0; i < s.length(); i++) {
switch(s[i]) {
case ')' : {
if (myList.empty())
return false;
iterator = myList.rbegin();
while (iterator != myList.rend() && *iterator != '(') {
iterator = next(iterator);
}
myList.erase(iterator == myList.rend() ? --myList.end() : --iterator.base());
}
break;
default: myList.push_back(s[i]); break;
}
}

iterator = myList.rbegin();
int star = 0;
while(iterator != myList.rend()) {
switch (*iterator) {
case '*' : star++; break;
case '(' :
if(star) --star;
else return false;
}
++iterator;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/11/PS/LeetCode/valid-parenthesis-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.