[LeetCode] Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

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
class Solution {
inline int _toString(string s) {
int res = 0;
int flag = isdigit(s[0]) ? 1 : -1;
for(int i = isdigit(s[0]) ? 0 : 1; i < s.length(); i++) res = (res<<3) + (res<<1) + (s[i] & 0b1111);
return flag * res;
}
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
unordered_map<string, function<int(int, int)>> m{
{"+", [](int n1, int n2) { return n1 + n2; }},
{"-", [](int n1, int n2) { return n1 - n2; }},
{"*", [](int n1, int n2) { return n1 * n2; }},
{"/", [](int n1, int n2) { return n1 / n2; }}
};

for (auto token : tokens) {
if(!m.count(token)) {
st.push(_toString(token));
} else {
int n1 = st.top(); st.pop();
int n2 = st.top(); st.pop();
st.push(m[token](n2, n1));
}
}
return st.top();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/26/PS/LeetCode/evaluate-reverse-polish-notation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.