An easy solution with stack


  • -1
    S
    bool isOperator(string str) {
        if (str == "+" || str == "-" || str == "*" || str == "/")
            return true;
        return false;
    }
    
    int evalRPN(vector<string> &tokens) {
        int ret = 0, a = 0, b = 0;
        stack<int> s;
        for (int i = 0; i < tokens.size(); ++i) {
            if (isOperator(tokens[i])) {
                b = s.top(); s.pop();
                a = s.top(); s.pop();
                if (tokens[i] == "+") ret = a + b;
                else if (tokens[i] == "-") ret = a - b;
                else if (tokens[i] == "*") ret = a * b;
                else ret = a / b;
                s.push(ret);
            }
            else {
                s.push(atoi(tokens[i].c_str()));
            }
        }
        
        return s.top();
    }

Log in to reply
 

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