forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsing-a-boolean-expression.cpp
40 lines (38 loc) · 1.03 KB
/
parsing-a-boolean-expression.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool parseBoolExpr(string expression) {
int i = 0;
return parse(expression, &i);
}
private:
bool parse(const string& expression, int *i) {
static const string ops = "&|!";
if (ops.find(expression[*i]) == string::npos) {
bool result = expression[*i] == 't';
++(*i);
return result;
}
const auto& op = expression[*i];
*i += 2;
vector<bool> stk;
while (expression[*i] != ')') {
if (expression[*i] == ',') {
++(*i);
continue;
}
stk.emplace_back(parse(expression, i));
}
++(*i);
if (op == '&') {
return all_of(stk.cbegin(), stk.cend(),
[](bool val) { return val; });
}
if (op == '|') {
return any_of(stk.cbegin(), stk.cend(),
[](bool val) { return val; });
}
return !stk[0];
}
};