A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:
't'that evaluates totrue.'f'that evaluates tofalse.'!(subExpr)'that evaluates to the logical NOT of the inner expressionsubExpr.'&(subExpr1, subExpr2, ..., subExprn)'that evaluates to the logical AND of the inner expressionssubExpr1, subExpr2, ..., subExprnwheren >= 1.'|(subExpr1, subExpr2, ..., subExprn)'that evaluates to the logical OR of the inner expressionssubExpr1, subExpr2, ..., subExprnwheren >= 1.
Given a string expression that represents a boolean expression, return the evaluation of that expression.
It is guaranteed that the given expression is valid and follows the given rules.
Example 1
Input: expression = "&(|(f))"
Output: false
Explanation:
First, evaluate |(f) --> f. The expression is now "&(f)".
Then, evaluate &(f) --> f. The expression is now "f".
Finally, return false.
Example 2
Input: expression = "|(f,f,f,t)"
Output: true
Explanation: The evaluation of (false OR false OR false OR true) is true.
Example 3
Input: expression = "!(&(f,t))"
Output: true
Explanation:
First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)".
Then, evaluate !(f) --> NOT false --> true. We return true.
Constraints
- 1 <= expression.length <= 2 * 1e4
- expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
Solution
外层循环遍历字符串,当遇到右括号进入出栈,否则把不是逗号的入栈
出栈时靠近栈顶的是若干 t f 序列,记录序列中 t 和 f 的个数,边记边出栈
遇到左括号表明 t f 序列遍历完毕,左括号出栈,读入布尔运算符
根据记录的 t f 数量进行运算,将结果入栈,继续字符串的遍历
class Solution {
public:
bool parseBoolExpr(string expression) {
stack<char> stk;
int n = expression.length();
for (int i = 0; i < n; i++) {
char c = expression[i];
if (c != ',') {
if (c != ')') {
stk.push(c);
} else {
int t = 0, f = 0;
while (stk.top() != '(') {
char val = stk.top();
stk.pop();
if (val == 't') t++;
else f++;
}
stk.pop();
char op = stk.top();
stk.pop();
switch (op) {
case '!':
stk.push(f == 1 ? 't' : 'f');
break;
case '&':
stk.push(f == 0 ? 't' : 'f');
break;
case '|':
stk.push(t == 0 ? 'f' : 't');
break;
default:
break;
}
}
}
}
return stk.top() == 't';
}
};