LeetCode—Evaluate Reverse Polish Notation解题报告
来源:互联网 发布:inspiration软件下载 编辑:程序博客网 时间:2024/05/24 06:28
转载请注明:http://blog.csdn.net/ict2014/article/details/17351145
原题如下:
题目解析:
简单明了的一句话就是:求解算术表达式的值。最经典的做法就是使用栈来解决此种问题。对于此道题目,我们使用一个“操作数栈”保存操作数,当遇到“操作符”的时候,就从栈中pop出两个元素,进行计算,然后将结果push至“操作数栈”中,然后继续进行扫描即可。最终“操作数栈”的栈顶就是我们所需要的结果。
算法的时间复杂度为O(n),空间复杂度最多为O(n/2)。
题目的代码如下:
//计算算术表达式的值//作者:张海波//时间:2013-12-16class Solution {public: //用栈保存操作数,遇到运算符就出栈两个运算数, //计算结果,然后将结果压入到栈中 int evalRPN(vector<string> &tokens) { stack<int> operands; int tokens_size = tokens.size(); int result, operand1, operand2; for(int i = 0; i < tokens_size; ++i) { if(IsOperator(tokens[i])){ operand1 = operands.top(); operands.pop(); operand2 = operands.top(); operands.pop(); result = CalculateArithmetic(operand2,tokens[i],operand1); operands.push(result); }else{ operands.push(atoi(tokens[i].c_str())); } } return operands.top(); } //判断字符是否为运算符 bool IsOperator(const string& ch){ for(int i = 0; i < 4; ++i){ if(ch == operators_[i]) return true; } return false; } //计算算术表达式的值 //operand1 _operator operand2 //例如:2 - 3 int CalculateArithmetic(const int& operand1, const string& _operator, const int& operand2){ int result = 0; if(_operator == operators_[0]){ result = operand1 + operand2; }else if(_operator == operators_[1]){ result = operand1 - operand2; }else if(_operator == operators_[2]){ result = operand1 * operand2; }else if(_operator == operators_[3]){ result = operand1 / operand2; } return result; }private: //运算符 string operators_[4] = {"+","-","*","/"};};
0 0
- [LeetCode]Evaluate Reverse Polish Notation, 解题报告
- leetcode解题报告 Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation 解题报告
- LeetCode—Evaluate Reverse Polish Notation解题报告
- [LeetCode OJ] Evaluate Reverse Polish Notation 解题报告
- [leetcode] 150. Evaluate Reverse Polish Notation 解题报告
- [Leetcode] 150. Evaluate Reverse Polish Notation 解题报告
- LeetCode——Evaluate Reverse Polish Notation
- LeetCode——Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- 心理学分析编程能力的四种境界
- unity3d中的http通信
- 导入项目出现乱码的解决办法
- rabbitmq使用说明--good
- 重写系统Crash处理类,保存Crash信息到SD卡 和 完美退出程序的方法
- LeetCode—Evaluate Reverse Polish Notation解题报告
- 黑马程序员 面向对象的概念
- Visual C# .Net 环境中编程实现浮动工具栏
- 去掉CodeIgniter URL中的index.php
- Effective C++ 第二版 45)幕后行为 46)编译链接和运行时错误 47)非局部静态对象初始化
- 找到饭碗,丢掉梦想
- Linux上安装MySQL,12条命令搞定MySql
- iOS strong 和weak的形象理解
- activity之间数据传递方式