时间轴

2025-11-19

init


题目:

经典题目,这里因为题目保证逆波兰表达式是合法的所以不做校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <string>
#include <vector>
#include <stack>

using std::vector;
using std::string;
using std::stack;

class Solution {
public:
int evalRPN(vector<string> &tokens)
{
stack<int> st;
int val1, val2, res = 0;
for (string &token : tokens) {
if (!token.compare("+") || !token.compare("-") || !token.compare("*") || !token.compare("/")) {
val1 = st.top();
st.pop();
val2 = st.top();
st.pop();
if (!token.compare("+")) {
st.push(val2 + val1);
} else if (!token.compare("-")) {
st.push(val2 - val1);
} else if (!token.compare("*")) {
st.push(val2 * val1);
} else if (!token.compare("/")) {
st.push(val2 / val1);
}
} else {
st.push(std::stoi(token));
}
}
return st.top();
}
};