0%

150. Evaluate Reverse Polish Notation

O(n) time O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (const auto &t : tokens) {
if (t.length() > 1 || isdigit(t[0])) { // 这里切记要检查长度是否大于1,因为有可能是负数!!
s.push(stoi(t));
} else {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
switch (t[0]) {
case '+': s.push(a + b); break;
case '-': s.push(a - b); break;
case '*': s.push(a * b); break;
case '/': s.push(a / b); break;
}
}
}
return s.top();
}
};