Evaluate Reverse Polish Notation
来源:互联网 发布:mac 照片 文件夹 分类 编辑:程序博客网 时间:2024/06/03 19:49
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
关键点:stack
思路:遇到数字则进栈,遇到操作符则取出栈顶的两个元素进行运算,要注意的是取出的元素和操作数顺序的关系。
代码:
public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < tokens.length; i++) { switch (tokens[i]) { case "+": stack.push(stack.pop() + stack.pop()); break; case "-": stack.push(-stack.pop() + stack.pop()); break; case "*": stack.push(stack.pop() * stack.pop()); break; case "/": int n1 = stack.pop(), n2 = stack.pop(); stack.push(n2 / n1); break; default: stack.push(Integer.parseInt(tokens[i])); } } return stack.pop(); }}
0 0
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 程序笔试题(涂鸦移动)
- 耳机插入笔记本还是有外音解决办法
- tomcat 容器生命周期lifecycle
- 分享的方法(个人工作遇到的问题,有第三方,也有官方的方法)
- 自定义可拖拽View(工具类ViewDragHelper的用法)
- Evaluate Reverse Polish Notation
- Android 网络交互
- Unity3D-射线Ray
- Unity3D核心类型
- tomact如何处理一个http请求?
- Unable to locate appropriate constructor on class原因分析
- iOS 导出 ipa 包时 三个选项的意义
- Listview属性大全
- 表示数值的字符串(模拟+剑指offer)