class Solution {
public:
bool parseBoolExpr(string expression) {
stack<char> cs1;//存储表达式
stack<char> cs2;//存储运算符!, |, &
for (int i = 0; i < expression.size(); i ++) {
int exp = expression[i];
if (exp == '"') continue;
if (exp == ')') {
//计算
char op = cs2.top();
cs2.pop();
string s = "";
while (cs1.size() && cs1.top() != '(') {
s += cs1.top();//由tf以及,组成的字符串
cs1.pop();
}
cs1.pop();//把(pop出去
if (op == '&') {
if (s.find('f') != s.npos) cs1.push('f');
else cs1.push('t');
}else if (op == '|'){
if (s.find('t') != s.npos) cs1.push('t');
else cs1.push('f');
}else {
if (s == "f") cs1.push('t');
else cs1.push('f');
}
}else if (exp == '!' || exp == '&' || exp == '|'){
//存储运算符
cs2.push(exp);
}else {
cs1.push(exp);
}
}
return cs1.top() == 't' ? true: false;
}
};
1106. 解析布尔表达式
最新推荐文章于 2022-11-05 22:12:23 发布