题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
struct Node {
double num;
char op;
bool is_num;
Node(): num(0.0), op('\0'), is_num(false) {}
};
class Solution {
private:
stack<Node> stk; //中缀表达式转后缀表达式存储运算符,之后计算后缀表达式存储数字
queue<Node> q; //存储后缀表达式
// 让左括号为最小优先级是因为其他运算符要在栈中都可以在左括号运算符之上
//这里括号只是标记作用,括号不入后缀表达式
unordered_map<char, int> prty{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'(', 0}};
public:
int solve(string s) {
// write code here
int len = s.size();
for (int i = 0; i < len; i++) {
if (s[i] == ' ')
continue;
Node node;
node.is_num = false;
if (s[i] == '(') {
node.op = s[i];
stk.push(node);
} else if (s[i] == ')') {
while (!stk.empty()) {
node = stk.top();
stk.pop();
if (node.op == '(')
break;
q.push(node);
}
} else if (isdigit(s[i])) {
node.num = 0.0;
node.is_num = true;
for (; i < len && isdigit(s[i]); i++) {
node.num = node.num * 10 + s[i] - '0';
}
i--;
q.push(node);
} else {
while (!stk.empty() && prty[stk.top().op] >= prty[s[i]]) {
q.push(stk.top());
stk.pop();
}
node.is_num = false;
node.op = s[i];
stk.push(node);
}
}
while (!stk.empty()) {
q.push(stk.top());
stk.pop();
}
// 计算后缀表达式
while (!q.empty()) {
Node tmp = q.front();
q.pop();
if (tmp.is_num) {
stk.push(tmp);
} else {
Node tmp2 = stk.top();
stk.pop();
Node tmp1 = stk.top();
stk.pop();
switch (tmp.op) {
case '+':
tmp.num = tmp1.num + tmp2.num;
break;
case '-':
tmp.num = tmp1.num - tmp2.num;
break;
case '*':
tmp.num = tmp1.num * tmp2.num;
break;
case '/':
tmp.num = tmp1.num / tmp2.num;
break;
}
stk.push(tmp);
}
}
return stk.top().num;
}
};