LeetCode150 Evaluate Reverse Polish Notation java题解
2015-06-30 10:13
495 查看
题目:
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:
解题:
这题是栈的一个经典应用,也比较简单,思路就是:遇到数字就进栈,遇到运算符号就出栈两个数字然后再将计算结果进栈。
代码:
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
解题:
这题是栈的一个经典应用,也比较简单,思路就是:遇到数字就进栈,遇到运算符号就出栈两个数字然后再将计算结果进栈。
代码:
import java.util.Stack; public class LeetCode150_EvaluateReversePolishNotation { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String[] s={"4","-2","/","2","-3","-","-"}; System.out.println(evalRPN(s)); } public static int evalRPN(String[] tokens) { int length=tokens.length; Stack<Integer> stack =new Stack<>(); for(int i=0;i<length;i++) { if(!isOperator(tokens[i])) stack.push(Integer.parseInt(tokens[i])); else { int operaNum2=stack.pop(); int operaNum1=stack.pop(); if(tokens[i].equals("+")) stack.push(operaNum1+operaNum2); else if(tokens[i].equals("-")) stack.push(operaNum1-operaNum2); else if(tokens[i].equals("*")) stack.push(operaNum1*operaNum2); else { stack.push(operaNum1/operaNum2); } } } return stack.pop(); } public static boolean isOperator(String s) { if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) return true; else return false; } }
相关文章推荐
- 读取xml生成lua测试代码
- Lua学习之类型与值
- Lua学习之类型与值
- Lua学习笔记之开始
- lua userdata
- lua垃圾回收机制
- Lua中使用二维数组实例
- lua学习--记录(2)
- Lua math.fmod使用时的小数问题
- .NET平台开源项目速览(8)Expression Evaluator表达式计算组件使用
- Ubuntu14.04 安装lua5.3
- Wireshark Lua插件学习心得
- Lua的string学习笔记
- Lua 与C/C++ 交互系列:动态注册枚举enum到Lua Code中,在运行时在Lua Code中获取内省信息
- LUA常见库和工具
- Lua 与C/C++ 交互系列:注册枚举enum到Lua Code中
- [文学阅读] METEOR: An Automatic Metric for MT Evaluation with Improved Correlation with Human Judgments
- lua string.dump
- 触摸精灵lua脚本实现微信群加好友功能
- lua中table如何安全移除元素