LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
来源:互联网 发布:海淘网站farfetch 知乎 编辑:程序博客网 时间:2024/06/06 18:07
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计算逆波兰式中算术表达式的值。
合法的操作符有+
, -
, *
, /
。每个操作数为整数或者另一个表达式。
例如:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6分析:
顺序扫描,遇见数字压栈,遇见操作符则从栈顶取出两个操作数(注意:先出栈的是第二个操作数),然后计算并将结果再压栈,重复此过程直到计算完毕,最后取出栈顶的元素即为结果值。
注意:下面的代码是假设输入的逆波兰式合法,没有考虑多余的操作符或者操作数不够的情况。可以通过检查栈的是否为空来达到检测的目的。
class Solution {public: int evalRPN(vector<string>& tokens) { if(tokens.empty()) { return 0; } int retVal = 0; bool isoperator = false; stack<int> tokenStack; int tokensSize = tokens.size(); for(int index = 0; index < tokensSize; ++index) { if(tokens[index] == "+" || tokens[index] == "-" || tokens[index] == "*" || tokens[index] == "/") { retVal = tokenStack.top();//如果为操作符,则取栈顶的两个元素参与计算 tokenStack.pop(); switch(tokens[index][0]) { case '+': { retVal += tokenStack.top(); } break; case '-': { retVal = tokenStack.top() - retVal; } break; case '*': { retVal *= tokenStack.top(); } break; case '/': { retVal = tokenStack.top() / retVal; } break; default: break; } tokenStack.pop();//删除第二个操作数 tokenStack.push(retVal); //计算结果压栈 } else //数字,转换后压栈 { tokenStack.push(atoi(tokens[index].c_str())); } } return tokenStack.top(); }};
0 0
- LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
- [C++]LeetCode: 98 Evaluate Reverse Polish Notation
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- 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
- 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
- POJ 1083 Moving Tables
- 三目运算及数据类型转换经典案例
- 转载_蓝牙物理链路类型:SCO和ACL链路
- 好久不学英语,差点忘了,赶紧整理!日期相关
- PATBasic——1008. 数组元素循环右移问题 (20)
- LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
- 毕业课题 ---opencv hog+svm bat批处理例子
- mongodb 在包含or条件查询的时候,尽量不使用排序
- py2exe笔记
- 分治算法 最接近点对(一维)
- python round(x)函数
- windows平台下如何用Python杀进程
- Python模块subprocess小记
- (转)如何使用Psyco为你的Python程序提速。