C++_O(n) Solution_13ms_66.35%


  • 0
    class Solution {
    public:
    int evalRPN(vector<string>& tokens) {
        int n = tokens.size();
        if( n == 0) return 0;
        stack<int> stk;
        
        for(int i = 0; i < n; i++){
            if((tokens[i] == "+") || (tokens[i] == "-") || (tokens[i] == "*") || (tokens[i] == "/")){
                int tmp2 = stk.top(); stk.pop();
                int tmp1 = stk.top(); stk.pop();
                int tmp_sum = 0;
                    if(tokens[i] == "+"){tmp_sum = tmp1 + tmp2;}
                    else if(tokens[i] == "-"){tmp_sum = tmp1 - tmp2;}
                    else if(tokens[i] == "*"){tmp_sum = tmp1 * tmp2;}
                    else if(tokens[i] == "/" && tmp2 != 0){tmp_sum = tmp1 / tmp2;}
                    else{return INT_MAX;}
                stk.push(tmp_sum);
            }else{
                stk.push(stoi(tokens[i]));
            }
        }
        return stk.top();
    }
    };
    

    0_1474662041590_203CE99C-537D-470A-A59D-AD9DF4AAF536.png


Log in to reply
 

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