A Simple 13ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
            stack<int> stk;
            int ans, operand1, operand2;
            for(int i = 0; i < tokens.size(); ++i) {
                if(tokens[i] != "") {
                    if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") stk.push(stoi(tokens[i]));
                    else {
                        if(stk.size() >= 2) {
                            operand2 = stk.top();
                            stk.pop();
                            operand1 = stk.top();
                            stk.pop();
                        } else return stk.top();
                        if(tokens[i] == "+") stk.push(operand1 + operand2);
                        if(tokens[i] == "-") stk.push(operand1 - operand2);
                        if(tokens[i] == "*") stk.push(operand1 * operand2);
                        if(tokens[i] == "/") stk.push(operand1 / operand2);
                    }
                }
            }
            return stk.top();
        }
    };
    

Log in to reply
 

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