My recursive c++ solution (15ms)


  • 0
    Y
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            int idx = tokens.size() - 1;
            return eval(tokens, idx);
        }
    
        int eval(vector<string> &tokens, int &idx) {
            int a, b;
            if ( tokens[idx] == "+" ) {
                --idx;
                b = eval(tokens, idx);
                a = eval(tokens, idx);
                return a + b;
            }
            else if ( tokens[idx] == "-" ) {
                --idx;
                b = eval(tokens, idx);
                a = eval(tokens, idx);
                return a - b;
            }
            else if ( tokens[idx] == "*" ) {
                --idx;
                b = eval(tokens, idx);
                a = eval(tokens, idx);
                return a * b;
            }
            else if ( tokens[idx] == "/" ) {
                --idx;
                b = eval(tokens, idx);
                a = eval(tokens, idx);
                return a / b;
            }
            else return stoi(tokens[idx--]);
        }
    };

Log in to reply
 

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