-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parenthesis_string.cpp
More file actions
109 lines (96 loc) · 2.93 KB
/
valid_parenthesis_string.cpp
File metadata and controls
109 lines (96 loc) · 2.93 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
678. Valid Parenthesis String
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 "".
Constraints:
1 <= s.length <= 100
s[i] is '(', ')' or '*'.
*/
// Recursion: time limit exceed
class Solution {
public:
bool checkValidString(string s) {
return check(s, 0, s.size(), 0);
}
bool check(string s, int idx, int sz, int curr){
if (idx == sz ) return curr == 0;
if (s[idx] == '(') {
return check(s, idx+1, sz, curr+1);
} else if (s[idx] == ')'){
if (curr== 0) return false;
return check(s, idx+1, sz, curr-1);
} else {
return check(s, idx+1, sz, curr) || check(s, idx+1, sz, curr+1) || (curr > 0 && check(s, idx+1, sz, curr-1));
}
}
};
// two stacks
class Solution {
public:
bool checkValidString(string s) {
stack<int> left, star;
for (int i = 0; i < s.size(); ++i){
if (s[i] == '(') left.push(i);
else if (s[i] == '*') star.push(i);
else {
if (!left.empty()) left.pop();
else if (!star.empty()) star.pop();
else return false;
}
}
while (! left.empty() && ! star.empty()){
if (left.top() > star.top() ) return false;
left.pop();
star.pop();
}
return left.empty();
}
};
// forward treating '*' as '(', then backward treating '*' as ')'
class Solution {
public:
bool checkValidString(string s) {
int ct = 0;
for (auto c : s){
if (c == ')'){
--ct;
if (ct < 0) return false;
} else ++ct;
}
if (ct == 0) return true;
ct = 0;
for (int i = s.size()-1; i>=0; --i){
if (s[i] == '(') {
--ct;
if (ct < 0) return false;
} else ++ct;
}
return true;
}
};
// high treating all '*' as '(', low treating '*' as ')' when possible
class Solution {
public:
bool checkValidString(string s) {
int high = 0;
int low = 0;
for (auto c : s){
if (c =='('){
++high;
++low;
} else if (c == ')'){
--high;
if (low > 0) --low; // meaning when possible
} else {
++high;
if (low > 0) --low; // meaning when possible
}
if (high < 0) return false;
}
return low == 0;
}
};