题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> oped;
for(auto it : tokens) {
//数字,进栈
if(isdigit(it[0]) || it.size() > 1) {
oped.push(atoi(it.c_str()));
}
//出栈两个数,计算后入栈
else {
int oped2 = oped.top();
oped.pop();
int oped1 = oped.top();
oped.pop();
switch (it[0]) {
case '+':
oped.push(oped1+oped2);
break;
case '-':
oped.push(oped1-oped2);
break;
case '*':
oped.push(oped1*oped2);
break;
case '/':
oped.push(oped1/oped2);
break;
}
}
}
return oped.top();
}
};
本文介绍了一种解决逆波兰表达式求值问题的方法。利用栈数据结构处理加减乘除运算,通过遍历字符串数组解析表达式并计算结果。示例展示了如何使用此方法求得逆波兰表达式的值。
307

被折叠的 条评论
为什么被折叠?



