-
Notifications
You must be signed in to change notification settings - Fork 3
/
678.cpp
49 lines (49 loc) · 1.27 KB
/
678.cpp
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
class Solution {
public:
bool checkValidString(string s) {
// check from left
int leftCount = 0;
int starCount = 0;
for (auto c : s) {
if (c == '(') leftCount++;
else if (c == ')') {
if (leftCount < 1) {
if (starCount == 0) return false;
else starCount--;
}
else {
leftCount--;
}
}
else {
starCount++;
}
}
if (leftCount != 0) {
if (leftCount > starCount) return false;
}
// check from right
int rightCount = 0;
starCount = 0;
for (int i = s.size() - 1; i >= 0; --i) {
char c = s[i];
if (c == ')') rightCount++;
else if (c == '(') {
if (rightCount < 1) {
if (starCount == 0) return false;
else starCount--;
}
else {
rightCount--;
}
}
else {
starCount++;
}
}
if (rightCount != 0) {
if (rightCount > starCount) return false;
}
return true;
}
};