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();
}
};
本文介绍了一种解决逆波兰表达式求值问题的方法。利用栈来存储数字,并使用哈希映射将运算符与相应的操作函数关联起来。当遇到数字时将其压入栈中,若遇到运算符则从栈顶取出两个数字进行运算并将结果重新压入栈中。
309

被折叠的 条评论
为什么被折叠?



