LeetCode 150. Evaluate Reverse Polish Notation 辅助数据结构栈
来源:互联网 发布:usb编程器 编辑:程序博客网 时间:2024/06/14 15:00
- 题目
- 题意
- 注意
- 思路
- 代码
- 结果
- 题目
题目
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
题意
用逆向波兰表示法计算算术表达式的值
注意
- 运算的种类 ( +, - ,*, / )
- 字符串表达的数字种类 (整数)
- 注意观察例子,表达式越靠前的运算符优先级越高,当遇到运算符后往前第一位数作为第二操作数,往钱的第二位数作为第一操作数。
思路
遇到数字压入栈中。这里判断字符串是否为数字不好写,转换思维识别运算符,余下的就是数字。
遇到运算符,弹出栈顶元素作为第二操作数,继续弹出栈顶元素作为第一操作数
得到的结果压入栈中作为下一轮运算的操作数
最终的结果存在了栈中,将栈顶元素返回即可
代码
class Solution {public: int evalRPN(vector<string>& tokens) { stack<int> sta; int calc = 0; //只有整型的计算,不涉及浮点型 int s1 = 0, s2 = 0; for (int i = 0; i < tokens.size(); i++) { string s = tokens[i]; if (s == "+") { s2 = sta.top(); sta.pop(); s1 = sta.top(); sta.pop(); calc = s1 + s2; sta.push(calc); } else if (s == "-") { s2 = sta.top(); sta.pop(); s1 = sta.top(); sta.pop(); calc = s1 - s2; sta.push(calc); } else if (s == "*") { s2 = sta.top(); sta.pop(); s1 = sta.top(); sta.pop(); calc = s1 * s2; sta.push(calc); } else if (s == "/") { s2 = sta.top(); sta.pop(); s1 = sta.top(); sta.pop(); calc = s1 / s2; sta.push(calc); } else { sta.push(stoi(s)); //stoi 字符串转整型 } } return sta.top(); //注意这个条件,最终是将结果放在了栈中 }};
结果
阅读全文
0 0
- LeetCode 150. Evaluate Reverse Polish Notation 辅助数据结构栈
- [leetcode] 【栈】150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150.Evaluate Reverse Polish Notation
- 【leetcode】150. Evaluate Reverse Polish Notation
- Leetcode 150. Evaluate Reverse Polish Notation
- [LeetCode]150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation LeetCode
- Leetcode 150. Evaluate Reverse Polish Notation
- leetcode 150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- LeetCode *** 150. Evaluate Reverse Polish Notation
- leetcode-150. Evaluate Reverse Polish Notation
- LeetCode-150.Evaluate Reverse Polish Notation
- leetcode.150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150. Evaluate Reverse Polish Notation
- LeetCode - 150. Evaluate Reverse Polish Notation
- fragment懒加载
- Git上传项目代码到github
- 1014. 福尔摩斯的约会 (20)
- Unity 3D 手机游戏开发学习随笔
- WebTours示例程序的订票流程-脚本
- LeetCode 150. Evaluate Reverse Polish Notation 辅助数据结构栈
- (91)调试面板
- json-c项目实战
- Devops学习实践(一) SVN安装和配置
- 《UNIX网络编程 卷1》 笔记: readline函数 (可重入版本)
- 【2014年第五届蓝桥杯C/C++程序设计本科B组决赛 信号匹配(代码填空) 】
- 明明的随机数
- PI监控Processed XML Messages
- LoadRunner测试webservice接口-方法一web_service_call()