classSolution {public:intevalRPN(vector<string>& tokens) { stack<int> stk;for(auto& tok: tokens) {if(tok !="+"&& tok !="-"&& tok !="*"&& tok !="/") {stk.push(stoi(tok)); }else {int n2 =stk.top();stk.pop();int n1 =stk.top();stk.pop();if(tok =="+")stk.push(n1+n2);elseif(tok =="-")stk.push(n1-n2);elseif(tok =="*")stk.push(n1*n2);elseif(tok =="/")stk.push(n1/n2); } }returnstk.top(); }};// idea: when we meet digits, we push it to stack// when we meet operator, we do calculations
Runtime: 12 ms, faster than 91.07% of C++ online submissions for Evaluate Reverse Polish Notation. Memory Usage: 11.4 MB, less than 93.04% of C++ online submissions for Evaluate Reverse Polish Notation.