LC150. Evaluate Reverse Polish Notation
1 min readApr 3, 2021
Discussion
A classical problem can be solved by using stack
Code
class Solution {
public:
stack<int> stk;
void eval(string op) {
auto b = stk.top(); stk.pop();
auto a = stk.top(); stk.pop();
if (op == "+") stk.push(a + b);
else if (op == "-") stk.push(a - b);
else if (op == "*") stk.push( a * b);
else stk.push(a / b);
return;
}
int evalRPN(vector<string>& tokens) {
unordered_set<string> op{"+", "-", "*", "/"};
for (auto & c : tokens) {
if (op.count(c)) eval(c);
else stk.push(stoi(c));
}
return stk.top();
}
};
Or
class Solution {
public:
stack<int> stack;
int evaluate(string operation){
auto b = stack.top();stack.pop();
auto a = stack.top();stack.pop();
if (operation == "+") return a + b;
if (operation == "-") return a - b;
if (operation == "*") return a * b;
if (operation == "/") return a / b;
return 0;
}
int evalRPN(vector<string>& tokens) {
unordered_set<string> operations = {"+", "-", "*", "/"};
for (auto &c : tokens) {
if (operations.count(c)) stack.push(evaluate(c));
else stack.push(stoi(c));
}
return stack.top();
}
};