题目:
![](https://i-blog.csdnimg.cn/blog_migrate/855f6d1fb9486994b776ba50d15eafb3.png)
代码(首刷看解析 2024年1月21日):
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" ||
tokens[i] == "*" || tokens[i] == "/") {
long long num1 = st.top();
st.pop();
long long num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
} else {
st.push(stoll(tokens[i]));
}
}
int result = st.top();
return result;
}
};
代码(二刷自解 2024年5月4日)
class Solution {
public:
// 入栈,当遇到+ - * /,取出2个数字进行运算,前算后
int to_int(string str) {
int res = 0;
istringstream ss(str);
ss>>res;
return res;
}
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (auto t : tokens) {
if (t == "+") {
int right = stk.top();
stk.pop();
stk.top() += right;
} else if (t == "-") {
int right = stk.top();
stk.pop();
stk.top() -= right;
} else if (t == "*") {
int right = stk.top();
stk.pop();
stk.top() *= right;
} else if (t == "/") {
int right = stk.top();
stk.pop();
stk.top() /= right;
} else {
stk.push(to_int(t));
}
}
return stk.top();
}
};