-
Notifications
You must be signed in to change notification settings - Fork 3
/
1106.cpp
47 lines (44 loc) · 1.17 KB
/
1106.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
class Solution {
public:
bool parseBoolExpr(string expression) {
stack<char> ops;
stack<vector<int>> values;
vector<int> nums;
int res;
int n = expression.size();
for (int i = 0; i < n; ++i) {
char c = expression[i];
if (c == '!' || c == '&' || c == '|') {
ops.push(c);
values.push(nums);
nums.clear();
i++;
}
else if (c == ')') {
char op = ops.top();
ops.pop();
res = eval(op, nums);
nums = values.top();
nums.push_back(res);
values.pop();
}
else if (c == 't' || c == 'f') {
nums.push_back(c == 't');
}
}
return res;
}
int eval(char op, vector<int>& nums) {
int res = 0;
if (op == '!') return !nums[0];
if (op == '&') {
res = 1;
for (auto& num : nums) res &= num;
}
else {
res = 0;
for (auto& num : nums) res |= num;
}
return res;
}
};