每天一道LeetCode-----后缀表达式求值

Evaluate Reverse Polish Notation

原题链接Evaluate Reverse Polish Notation

每天一道LeetCode-----后缀表达式求值_第1张图片

后缀表达式求值,用栈即可

代码如下

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        unordered_map<string, std::function<int(int, int)>> opMap;
        opMap["+"] = [](int a, int b) { return a + b; };
        opMap["-"] = [](int a, int b) { return a - b; };
        opMap["*"] = [](int a, int b) { return a * b; };
        opMap["/"] = [](int a, int b) { return a / b; };
        stack<int> s;
        for(auto& token : tokens)
        {
            auto p = tryConvertToInt(token);
            if(p.second)
                s.push(p.first);
            else
            {
                int b = s.top();
                s.pop();
                int a = s.top();
                s.pop();
                s.push(opMap[token](a, b));
            }
        }
        return s.top();
    }
private:
    std::pair<int, bool> tryConvertToInt(const string& token)
    {
        int n = 0;
        int res = ::sscanf(token.c_str(), "%d", &n);
        if(res == 0)
            return std::make_pair(n, false);
        else
            return std::make_pair(n, true);
    }
};

你可能感兴趣的:(LeetCode)