Short 16ms C++ solution with stack


  • 0
    D
    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
            stack<int> s;
            for (auto t : tokens) {
                if (t == "+" || t == "-" || t == "*" || t == "/") {
                    int y = s.top(); s.pop();
                    int x = s.top(); s.pop();
                    int z = 0;
                    switch (t.front()) {
                        case '+' :
                            z = x + y;
                            break;
                        case '-' :
                            z = x - y;
                            break;
                        case '*' :
                            z = x * y;
                            break;
                        case '/' :
                            z = x / y;
                            break;
                    }
                    s.push(z);
                } else {
                    s.push(stoi(t));
                }
            }
            return s.top();
        }
    };

Log in to reply
 

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