题意:后序运算。
思路:使用堆栈储存操作对象。
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();
}
};