LeetCode -- Evaluate Reverse Polish Notation
来源:互联网 发布:吉利知豆好不好 编辑:程序博客网 时间:2024/05/18 03:14
题目如下:
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> stk; for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) { if(isOper(*it) ){ int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(rst(a, b, *it)); }else{ stk.push(numb(*it)); } } return stk.top(); } int numb(string s) { int ret = 0, flag = 1; size_t i = 0; if(s[i] == '-'){ flag = -1; ++i; }else if(s[i] == '+'){ ++i; } for(; i < s.length(); ++i) { ret = ret*10 + (s[i] - '0'); } return ret*flag; } int rst(int a, int b, string op) { if(op == "+") return a+b; else if(op == "-") return a-b; else if(op == "*") return a*b; else if(op == "/") return a/b; } bool isOper(string s){ return (s == "+" || s == "-" || s == "*" || s == "/"); }};代码中,用isOper判断元素是运算符还是数字,如果是运算符就从栈中取两个数字,用rst来做计算,如果是数字的话就转化位数字直接进栈。
在进行数字转化的时候,考虑了数字符号为正和为负两种情况,不知道LeetCode的测试用例有没有考虑到这个情况。
代码的长度还是比较长的,可以进一步优化,不过这么写,更容易看懂吧
0 0
- 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
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- ext4.1入门
- oracle 数据库字符集研究 上篇
- C# 中的EventHandler
- 关于dialog的一点东西
- poj 2823 Sliding Window
- LeetCode -- Evaluate Reverse Polish Notation
- UVA 10591 - Happy Number
- Mifare l射频卡初始值及其相关说明
- multiple lua files with same-named functions
- Raspberry Pi B+ 定时向物联网yeelink上传CPU GPU温度
- 【SPOJ】13041 The Black Riders 二分最大流
- 对于原生代码使用Java线程的优缺点
- Excel和vs2010 的连接(续)
- SD卡存储图片的工具类