LeetCode 150 Evaluate Reverse Polish Notation
概述
https://leetcode.com/problems/evaluate-reverse-polish-notation/
解法
用一个堆栈就好了。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (auto t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int r = s.top(); s.pop();
int l = s.top(); s.pop();
int res = 0;
switch (t[0]) {
case '+':
res = l + r;
break;
case '-':
res = l - r;
break;
case '*':
res = l * r;
break;
case '/':
res = l / r;
break;
}
s.push(res);
} else {
s.push(stoi(t));
}
}
return s.top();
}
};