您的位置:首页 > 编程语言 > Lua

[LeetCode]150. Evaluate Reverse Polish Notation

2017-03-20 21:21 507 查看

150. Evaluate Reverse Polish Notation

题目描述



思路

遇到数字压栈,遇到运算符出栈运算,结果压栈

整体思路比较简单,看讨论区有设计到C++的函数式编程,留在这里记录一下

代码

class Solution {
public:
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int(int, int) > > map = {
{ "+" , [](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; } }
};
std::stack<int> stack;
for (string& s : tokens) {
if (!map.count(s)) {
stack.push(stoi(s));
}
else {
int op1 = stack.top();
stack.pop();
int op2 = stack.top();
stack.pop();
stack.push(map[s](op2, op1));
}
}
return stack.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: