Concise and easy to extend C++ code


  • 0
    G
    class Solution {
        map<string, function<int(int, int)>> action;
    public:
        Solution() {
            action["+"] = [](int x, int y) {return x + y;};
            action["/"] = [](int x, int y) {return x / y;};
            action["*"] = [](int x, int y) {return x * y;};
            action["-"] = [](int x, int y) {return x - y;};
        }
        
        int evalRPN(vector<string>& tokens) {
            string s = tokens.back();
            tokens.pop_back();
            if(action.find(s) != action.end()) {
                int left = evalRPN(tokens);
                int right = evalRPN(tokens);
                return action[s](right, left);
            }else {
                return atoi(s.c_str());
            }
        }
    };

Log in to reply
 

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