题意:后序运算。
思路:使用堆栈储存操作对象。
class Solution {
public:
stack<int> ms;
int evalRPN(vector<string>& tokens) {
for(int i = 0; i < tokens.size(); ++ i) {
if(tokens[i][0] == '+' && tokens[i].length() == 1) {
int a = ms.top();
ms.pop();
int b = ms.top();
ms.pop();
ms.push(b + a);
}
else if (tokens[i][0] == '-' && tokens[i].length() == 1) {
int a = ms.top(); ms.pop();
int b = ms.top(); ms.pop();
ms.push(b - a);
}
else if (tokens[i][0] == '*' && tokens[i].length() == 1) {
int a = ms.top(); ms.pop();
int b = ms.top(); ms.pop();
ms.push(b * a);
}
else if (tokens[i][0] == '/' && tokens[i].length() == 1) {
int a = ms.top(); ms.pop();
int b = ms.top(); ms.pop();
ms.push(b / a);
}
else ms.push(std::stoi(tokens[i]));
}
return ms.top();
}
};

本文介绍了一种使用堆栈实现后序表达式(逆波兰表示法)计算的方法。通过遍历表达式,遇到操作数则压入堆栈,遇到运算符则从堆栈中弹出两个操作数进行计算并将结果压回堆栈。
157

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



