Short C++ O(n) time non-recursive solution


  • 0
    class Solution {
    public:
        int evalRPN(vector<string>& tokens) { 
            stack<int> stk;  
            for(auto s: tokens){
                if(s.size() == 1 && !isdigit(s[0])){ // operator
                    int n2 = stk.top(); stk.pop();
                    int n1 = stk.top(); stk.pop();
                    if(s[0] == '+') stk.push(n1 + n2);
                    if(s[0] == '-') stk.push(n1 - n2);
                    if(s[0] == '*') stk.push(n1 * n2);
                    if(s[0] == '/') stk.push(n1 / n2);
                }else stk.push(stoi(s));             
            }
            
            return stk.top();   
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.