150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression inReverse Polish Notation.
Valid operators are+
,-
,*
,/
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
S: stack O(n)
int evalRPN(vector<string>& tokens) {
if (tokens.size() == 0) return 0;
stack<int> nums;
unordered_set<string> operators{"+", "-", "*", "/"};
for (const string& s : tokens) {
if (operators.find(s) == operators.end()) {
nums.push(stoi(s));
} else {
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
if (s == "+") {
nums.push(a + b);
} else if (s == "-") {
nums.push(a - b);
} else if (s == "*") {
nums.push(a * b);
} else if (s == "/") {
nums.push(a / b);
}
}
}
return nums.top();
}