LeetCode算法题目:Evaluate Reverse Polish Notation
来源:互联网 发布:mac可清除空间如何清除 编辑:程序博客网 时间:2024/05/22 17:06
题目:
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
分析:
逆波兰式计算等式非常容易,利用堆栈即可完成。另外,程序中还需要实现整数与字符串之间的相互转换。
这题目以前做过,所以一遍AC。
代码:
class Solution {public: int evalRPN(vector<string>& tokens) { int len=tokens.size(); stack<int> S; for(int i = 0; i < len; i++) { if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int op2 = S.top(); S.pop(); int op1 = S.top(); S.pop(); S.push( op(op1, op2, tokens[i][0]) ); } else S.push(stoi(tokens[i]));//stoi() 把字符串转换成数字 } return S.top(); } int op(int op1, int op2, char optor) { if(optor == '+')return op1 + op2; else if(optor == '-')return op1 - op2; else if(optor == '*')return op1 * op2; else return op1 / op2; }};
0 0
- 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
- 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
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- Python爬虫—1入门_4_正则表达式
- iOS的GCDAsyncSocket快速开发Socket通信
- 算法提高 学霸的迷宫
- 岁月如初dfs poj1321 (类八皇后问题)
- Unity GUI的使用2
- LeetCode算法题目:Evaluate Reverse Polish Notation
- android--toolbar和侧滑结合的简单实现
- mybatis_02
- Unity3D引擎之渲染技术系列六
- Java中List或者HashMap对象-序列化和反序列化并附读写文件操作
- 闭包作用域
- 结对编程 软件工程
- iptables 日志拦截
- IIS中ftp的部署+防火墙(一)