-
Notifications
You must be signed in to change notification settings - Fork 0
/
150-Evaluate Reverse Polish Notation.cpp
53 lines (52 loc) · 1.7 KB
/
150-Evaluate Reverse Polish Notation.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
unordered_map<string, function<int(int,int)>> fun = {
{"+", [](int a, int b){return a + b;}},
{"-", [](int a, int b){return a - b;}},
{"*", [](int a, int b){return a * b;}},
{"/", [](int a, int b){return a / b;}}
};
for(auto token : tokens) {
const auto& op = fun.find(token);
if(op != fun.end()){
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push((*op).second(a, b));
} else
stk.push(stoi(token));
}
return stk.top();
}
};
// class Solution {
// public:
// int evalRPN(vector<string>& tokens) {
// stack<string> stk;
// for(auto i : tokens) {
// if(i == "+" || i == "-" || i == "*" || i == "/"){
// string right = stk.top();
// stk.pop();
// string left = stk.top();
// stk.pop();
// stk.push(expression(left, right, i));
// } else{
// stk.push(i);
// }
// }
// return stoi(stk.top());
// }
// string expression(string left, string right, string op) {
// string res;
// if(op == "+")
// res = to_string(stoi(left)+stoi(right));
// else if(op == "-")
// res = to_string(stoi(left)-stoi(right));
// else if(op == "*")
// res = to_string(stoi(left)*stoi(right));
// else if(op == "/")
// res = to_string(stoi(left)/stoi(right));
// return res;
// }
// };