LeetCode:Evaluate Reverse Polish Notation
来源:互联网 发布:时光不语静待花开知乎 编辑:程序博客网 时间:2024/06/03 21:23
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个数字进行相应计算,并将结果压栈,结束后从栈中弹出结果。
public class Solution { public int evalRPN(String[] tokens) { int len=tokens.length; Stack<Integer> stack=new Stack<Integer>(); int num1,num2; for(int i=0;i<len;i++) { if(tokens[i].equals("+")) { num2=stack.pop(); num1=stack.pop(); stack.add(num1+num2); continue; } if(tokens[i].equals("-")) { num2=stack.pop(); num1=stack.pop(); stack.add(num1-num2); continue; } if(tokens[i].equals("*")) { num2=stack.pop(); num1=stack.pop(); stack.add(num1*num2); continue; } if(tokens[i].equals("/")) { num2=stack.pop(); num1=stack.pop(); stack.add(num1/num2); continue; } stack.add(Integer.valueOf(tokens[i])); } return stack.pop(); }}
0 0
- 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
- 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
- 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
- Cocos2d入门及第一次运行时遇到的问题
- HttpURLConnection、HttpClient和Session
- 在Android上使用Socket
- Understand Your Project Costs in an Engineer-to-Order Manufacturing Environment
- Ubuntu12.04+下安装Google Chrome
- LeetCode:Evaluate Reverse Polish Notation
- XShell技巧分享
- JSTL截取字符串以及格式化时间
- lua math库
- 光流法
- LUA string库详解
- 马航飞机失踪,马航产品遭华服务提供商停售
- windows下编译ffmpeg
- log日志--logback--日志文件例子