Evaluate Reverse Polish Notation
来源:互联网 发布:淘宝做代理赚钱吗 编辑:程序博客网 时间:2024/06/03 13:15
Evaluate Reverse Polish Notation
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
该题为逆波兰式求值,算法比较简单。用栈保存数字,遇到数字入栈,遇到运算符栈顶两元素出栈求值,结果再入栈,最后栈顶元素就是结果。 但是写起来比较费事,可以这样写:
int evalRPN(vector<string>& tokens) { stack<int> nums; int result, t1, t2; for (auto t : tokens) { if (t == "+") { t1 = nums.top(); nums.pop(); t2 = nums.top(); nums.pop(); nums.push(t2 + t1); } else if (t == "-") { t1 = nums.top(); nums.pop(); t2 = nums.top(); nums.pop(); nums.push(t2 - t1); } else if (t == "*") { t1 = nums.top(); nums.pop(); t2 = nums.top(); nums.pop(); nums.push(t2 * t1); } else if (t == "/") { t1 = nums.top(); nums.pop(); t2 = nums.top(); nums.pop(); nums.push(t2 / t1); } else { nums.push(stoi(t)); } } return nums.top();}
也可以使用c++11的function, 如下:
int evalRPN(vector<string>& tokens) { stack<int> nums; unordered_map<string, function<int(int, int)>> operators = { {"+", std::plus<int>() }, { "-", std::minus<int>() }, { "*", std::multiplies<int>() }, { "/", std::divides<int>() } }; int result, t1, t2; for (auto t : tokens) { if (operators.count(t)) { t1 = nums.top(); nums.pop(); t2 = nums.top(); nums.pop(); nums.push(operators[t](t2, t1)); } else { nums.push(stoi(t)); } } return nums.top();}
是不是简单很多。
0 0
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Map中entry的源代码
- Android学习笔记(3):Android项目结构分析
- 【ZYNQ-7000开发之三】ZYNQ平台的HDMI驱动测试
- 第14章1节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-面向控件编程VS面向坐标编程
- 第14章2节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-HierarchyViewer架构概述
- Evaluate Reverse Polish Notation
- Android学习笔记(4):资源字典R.java
- 第14章3节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-HierarchyViewer实例化
- (八十二)if语句
- 第14章4节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-装备ViewServer-端口转发
- 第14章5节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-装备ViewServer-查询ViewServer运行状态
- (八十三)逻辑表达式
- 第14章6节《MonkeyRunner源码剖析》 HierarchyViewer实现原理-装备ViewServer-启动ViewServer
- [转载]pandoc ~.md->pdf