https://leetcode.com/problems/evaluate-reverse-polish-notation/?tab=Description
开一个栈,遇到数字压栈,遇到运算符就从栈中弹出两个元素做相应的计算然后再压回去。
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
if (tokens.empty()) return 0;
if (tokens.size() == 1) return stoi(tokens[0]);
stack<int> stk;
int ret = 0;
for (int i = 0; i < tokens.size(); ++i) {
string& str = tokens[i];
if (isop(str)) {
int x = stk.top(); stk.pop();
int y = stk.top(); stk.pop();
if (str == "+") {
ret = y + x;
} else if (str == "-") {
ret = y - x;
} else if (str == "*") {
ret = y * x;
} else {
ret = y / x;
}
stk.push(ret);
} else {
stk.push(stoi(str));
}
}
return ret;
}
private:
bool isop(string& str) {
return (str == "+" || str == "-" || str == "*" || str == "/");
}
};