思路:
当字符串为运算符号是弹出栈中两个数字进行运算
stoi("1") 将string转换为int
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stack;
for (int i = 0; i < tokens.size(); i ++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int num1 = stack.top();
stack.pop();
int num2 = stack.top();
stack.pop();
if (tokens[i] == "+") stack.push(num2 + num1);
else if (tokens[i] == "-") stack.push(num2 - num1);
else if (tokens[i] == "*") stack.push(num2 * num1);
else stack.push(num2 / num1);
}
else stack.push(stoi(tokens[i]));
}
int res = stack.top();
return res;
}
};
标签:150,num1,num2,int,stack,tokens,push,求值,LeetCode
From: https://www.cnblogs.com/hjy94wo/p/16629881.html