leetcode No150. Evaluate Reverse Polish Notation

来源:互联网 发布:软件开发图片 编辑:程序博客网 时间:2024/06/11 20:36

Question

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

Algorithm

逆波兰表达式求值,用栈解决问题,我还在Solutions中看到了lambda表达式的解法,很有趣
https://discuss.leetcode.com/topic/38178/fancy-c-lambda-expression-solution

Accepted Code

一般解法:

class Solution {public:    int evalRPN(vector<string>& tokens) {        stack<int> s;        for(int i=0;i<tokens.size();i++)        {            if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/")            {                s.push(stoi(tokens[i]));            }            else            {                int b=s.top();                s.pop();                int a=s.top();                s.pop();                if(tokens[i]=="+")                    s.push(a+b);                else if(tokens[i]=="-")                    s.push(a-b);                else if(tokens[i]=="*")                    s.push(a*b);                else                    s.push(a/b);            }        }        return s.top();    }};

lambda表达式解法

class Solution {public:    int evalRPN(vector<string>& tokens) {        unordered_map<string,function<int (int,int)>> hash={            {"+",[](int a,int b){return a+b;}},            {"-",[](int a,int b){return a-b;}},            {"*",[](int a,int b){return a*b;}},            {"/",[](int a,int b){return a/b;}},        };        stack<int> s;        for(auto i:tokens)        {            if(hash[i]==0)            {                s.push(stoi(i));            }            else            {                int b=s.top();                s.pop();                int a=s.top();                s.pop();                s.push(hash[i](a,b));            }        }        return s.top();    }};