12 ms c++ simple solution , beats 96%


  • 0
    G

    class Solution {
    public:
    int evalRPN(vector<string>& tokens) {
    stack<int> stk;
    int op1 , op2 , res;
    for(int i = 0 ; i < tokens.size() ; i++)
    {
    string tkn = tokens[i];
    if(!tkn.compare("+") || !tkn.compare("-") || !tkn.compare("*") || !tkn.compare("/"))
    {
    int op1 = stk.top();
    stk.pop();
    int op2 = stk.top();
    stk.pop();
    res = doOp(tkn,op1,op2);
    stk.push(res);
    }else{
    stk.push(stoi(tkn));
    }
    }
    return stk.top();
    }

    int doOp(string str, int op1 , int op2)
    {
        switch(str[0])
        {
            case '+':
                return op1 + op2;
                break;
            case '-':
                return op2 - op1;
                break;
            case '*':
                return op1 * op2;
                break;
            case '/':
                return op2 / op1;
                break;
            default:
                break;
        }
        return 0;
    }
    

    };


Log in to reply
 

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