-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
71 lines (66 loc) · 2.24 KB
/
Solution.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <cassert>
#include <cstddef>
#include <functional>
#include <string>
#include <string_view>
using namespace std;
class Solution {
private:
bool evaluate(string_view expression,
int& idx,
bool init,
function<bool(bool, bool)> op) {
++idx; // skip '('
while (idx < expression.length() && expression[idx] != ')') {
// The first token in a bracket will not be a comma.
bool subExpr = parseExpr(expression, idx);
init = op(init, subExpr);
if (expression[idx] == ')') {
// end of subexpression. Another check is required here, because
// parseExpr increased idx.
// This is for e.g. !(&(...), ...) where the closing parentheses is
// followed by a comma, resulting in wrong evaluation.
break;
}
++idx; // skip ','
}
++idx; // skip ')'
return init;
}
bool parseExpr(string_view expression, int& idx) {
const char token = expression[idx++];
switch (token) {
case 't':
return true;
case 'f':
return false;
case '!':
return evaluate(expression, idx, false,
[](bool init, bool subExpr) { return !subExpr; });
case '&':
return evaluate(expression, idx, true,
[](bool init, bool subExpr) { return init & subExpr; });
case '|':
return evaluate(expression, idx, false,
[](bool init, bool subExpr) { return init | subExpr; });
}
// should not reach here. Indicates invalid input
assert("invalid input");
return false;
}
public:
bool parseBoolExpr(string_view expression) {
// 't' evaluates to true
// 'f' evaluates to false
// "!(expression)" evaluates to logical NOT
// "&(expression...)" evaluates to logical AND
// "|(expression...)" evaluates to logical OR
// Seems similar to 394 - Decode String
// Seems like if expression is length 1, it must be a plain 't' or
// 'f'. The next possible expression would be something like "!(t)",
// which is of length 4. Then !(&(t,t)) => length 9. There cant be
// something like (t, t), where there is no boolean operator.
int idx = 0;
return parseExpr(expression, idx);
}
};