[LeetCode] Parsing A Boolean Expression

1106. Parsing A Boolean Expression

Return the result of evaluating a given boolean expression, represented as a string.

An expression can either be:

  • “t”, evaluating to True;
  • “f”, evaluating to False;
  • “!(expr)”, evaluating to the logical NOT of the inner expression expr;
  • “&(expr1,expr2,…)”, evaluating to the logical AND of 2 or more inner expressions expr1, expr2, …;
  • “|(expr1,expr2,…)”, evaluating to the logical OR of 2 or more inner expressions expr1, expr2, …
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
class Solution {
bool evalAnd(string& exp, int& p) {
p += 2;
auto res = true;
res &= eval(exp, p);
while(exp[p] != ')') {
p++;
res &= eval(exp, p);
}
p++;
return res;
}
bool evalOr(string& exp, int& p) {
p += 2;
auto res = false;
res |= eval(exp, p);
while(exp[p] != ')') {
p++;
res |= eval(exp, p);
}
p++;
return res;
}
bool evalNot(string& exp, int& p) {
p += 2;
auto res = eval(exp, p);
p++;
return !res;
}
bool eval(string& exp, int& p) {
if(exp[p] == 't') {
p++;
return true;
} else if(exp[p] == 'f') {
p++;
return false;
} else if(exp[p] == '&') {
return evalAnd(exp, p);
} else if(exp[p] == '|') {
return evalOr(exp, p);
} else return evalNot(exp, p);
}
public:
bool parseBoolExpr(string expression) {
int pos = 0;
return eval(expression, pos);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/LeetCode/parsing-a-boolean-expression/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.