LeetCode 150. Evaluate Reverse Polish Notation
来源:互联网 发布:图像处理算法 编辑:程序博客网 时间:2024/06/02 00:19
- 题目
- 题意
- 分析
- 代码
题目
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
题意
计算出逆波兰表达式(Reverse Polish Notation)的值。
合法的操作符是+
, -
, *
, /
。每一个操作数可以是整数或者另一种表达式。
下面是一些例子:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
分析
逆波兰表达式又叫做后序表达式,我们常看到的表达式为中序表达式,比如a+b
,表示为ab+
。人的大脑适合理解中序表达式,但是计算机比较倾向于逆波兰表达式。
逆波兰表达式的优势在于只用两种简单操作,入栈和出栈就可以搞定任何普通表达式的运算。其运算方式如下:
如果当前字符为变量或者为数字,则进栈,如果是运算符,则将栈顶两个元素弹出作相应运算,结果再入栈最后当表达式扫描完后,栈里的就是结果。
代码
int evalRPN(vector<string>& tokens) { stack<int> myStack; int temp; for(int i=0;i<tokens.size();i++){ if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){ temp = myStack.top(); myStack.pop(); if(tokens[i] == "+") temp += myStack.top(); else if(tokens[i] == "-") temp = myStack.top() - temp; else if(tokens[i] == "*") temp *= myStack.top(); else if(tokens[i] == "/") temp = myStack.top() / temp; myStack.pop(); myStack.push(temp); } else myStack.push(stoi(tokens[i].c_str())); } return myStack.top();}
20 / 20 test cases passed.
Runtime: 9 ms
阅读全文
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
- 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
- LeetCode - 150. Evaluate Reverse Polish Notation
- [LeetCode] 150. Evaluate Reverse Polish Notation
- View的事件分发机制详解
- imf瞬时频率跳变问题
- 冰雕
- 数据结构-----Trie树
- js预解析
- LeetCode 150. Evaluate Reverse Polish Notation
- java集合框架
- React-Native中的flexbox布局的使用
- Java中的基础----堆与栈的介绍、区别
- 通讯录小项目(C语言动态版本)
- java注解
- 定位详解
- Java实现PDF打印的解决方案
- Android自定义可标记日历