LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
来源:互联网 发布:淘宝小崔韩代 编辑:程序博客网 时间:2024/06/13 12:40
150. 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
从左到右遍历表达式的每个数字和字符,遇到数字就进栈,遇到符号,就将栈顶的两个数字取出(注意第一次取出的是右操作数,第二次取出的栈顶数字是左操作数),进行运算,将运算结果压栈,一直到最终获得计算结果(最终的栈顶数字)。
逆波兰式求值(后缀表达式)
public int evalRPN(String[] tokens) {int len;if ((len = tokens.length) == 0)return 0;Stack<Integer> stk = new Stack<>();for (int i = 0; i < len; i++) {try {int tmp = Integer.valueOf(tokens[i]);stk.push(tmp);} catch (Exception e) {// 栈的弹出顺序,先弹后面int sec = stk.pop();// 处理一个数字是负数的情况如{"3", "-" }// 或者 { "6", "3", "*", "-" }int fir = 0;if (!stk.isEmpty())fir = stk.pop();int tmp = 0;if (tokens[i].equals("+"))tmp = fir + sec;if (tokens[i].equals("-"))tmp = fir - sec;if (tokens[i].equals("*"))tmp = fir * sec;if (tokens[i].equals("/"))tmp = fir / sec;stk.push(tmp);}}return stk.pop();}
0 0
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- LeetCode:150. Evaluate Reverse Polish Notation(逆波兰表达式)
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- 逆波兰表达式求值(Evaluate Reverse Polish Notation)
- LeetCode | Evaluate Reverse Polish Notation(逆波兰式求值)
- Leetcode 150 Evaluate Reverse Polish Notation (求值逆波兰表达式)
- 【LeetCode】Evaluate Reverse Polish Notation(逆波兰表达式求值) -(Linkedin) Medium ++
- leetcode Evaluate Reverse Polish Notation(计算逆波兰表达式)
- [Leetcode] Evaluate Reverse Polish Notation 逆波兰表达式
- Evaluate Reverse Polish Notation 逆波兰表达式
- Java Evaluate Reverse Polish Notation(逆波兰表达式)
- Java实现逆波兰表达式(Evaluate Reverse Polish Notation)
- 150. Evaluate Reverse Polish Notation 逆波兰表达式
- 【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现
- Leetcode刷题记——150. Evaluate Reverse Polish Notation(计算逆波兰表达式)
- leetcode 150. Evaluate Reverse Polish Notation 逆波兰表达式的计算
- Evaluate Reverse Polish Notation--逆波兰式求值
- A+B Problem IV
- HDU-5858 Hard problem(计算几何)
- 创建Stream
- hadoop报错解决方案---安装系列三
- 做游戏,学编程(C语言) 3 利用函数对飞机游戏进行重构
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- PHP设计模式系列(十一):状态模式
- 做游戏,学编程(C语言) 4 flappy bird
- SpringBoot非官方教程 | 第十四篇:在springboot中用redis实现消息队列
- 文章标题
- JAVA之键盘,鼠标监听事件
- java中讲讲InputStreamReader的用法,举例?
- 程序员创业的情怀和梦想
- 树的子结构