1908 · Boolean expression evaluation
Algorithms
Hard
Accepted Rate
37%
Description
Solution
Notes
Discuss
Leaderboard
Record
Description
Given a string represents a Boolean expression only including “true”,“false”,“or”,“and”.
Your task is to calculate the result of the expression by returning “true” or “false”.
If the expression is not valid, you need to return a string “error”.
We promise that there are no more than 1000010000 elements in the expression.
There are only 4 kinds of elements in the expression : “true”, “false”, “and”, “or”.
Example
Example 1
Input:
“true and false”
Output:
“false”
Example 2
Input:
“true or”
Output:
“error”
Tags
Company
Meituan
解法1:用stack, 类似LintCode 368 Expression Evaluate那题,中序表达式转RPN后求值。注意LintCode 368那题不需要检查表达式是否有错,这题需要,所以就判断"and"和"or“前后是不是"true"和"false"即可。
class Solution {
public:
/**
* @param expression: a string that representing an expression
* @return: the result of the expression
*/
string evaluation(string &expression) {
stack<string> optrStk;
vector<string> RPNExpr;
map<string, int> prio;
prio["and"] = 2;
prio["or"] = 1;
prio["true"] = 0;
prio["false"] = 0;
//tokenize
stringstream ss(expression);
vector<string> tokens;
string token;
while (ss >> token) tokens.push_back(token);
int len = tokens.size();
//transform it to RPN
for (int i = 0; i < len; i++)
{
string expr = tokens[i];
if (expr == "true" || expr == "false") {
RPNExpr.push_back(expr);
continue;
}
if (i == 0 || i == len - 1) return "error"; //"and" or "or" is the first token or last token, error!
if (prio[tokens[i - 1]] > 0 || prio[tokens[i + 1]] > 0) return "error";
while (!optrStk.empty() && prio[optrStk.top()] >= prio[expr]) {
RPNExpr.push_back(optrStk.top());
optrStk.pop();
}
optrStk.push(expr);
}
//dump the rest in optrStr to RPNExpr
while (!optrStk.empty()) {
RPNExpr.push_back(optrStk.top());
optrStk.pop();
}
//now evaluate RPN
bool ret;
len = RPNExpr.size();
stack<bool> RPNStk;
if (len == 0 || len == 2) return "error";
for (int i = 0; i < len; i++) {
string expr = RPNExpr[i];
if (expr == "true" || expr == "false") {
RPNStk.push(expr == "true");
} else {
bool first = RPNStk.top(); RPNStk.pop();
bool second = RPNStk.top(); RPNStk.pop();
if (expr == "and") {
RPNStk.push(first && second);
} else { //expr == "or"
RPNStk.push(first || second);
}
}
}
if (RPNStk.top()) return "true";
return "false";
}
};
解法2:这题应该也可以用递归解,先找出优先级最低的那个符号,然后左右递归求值。