150. Evaluate Reverse Polish Notation
2016-04-24 19:39
423 查看
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:
思路:就是用栈来实现后缀式也就是逆波兰式的计算过程
代码如下(已通过leetcode)
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack<String>();
for(String s:tokens) {
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) {
int dig2=Integer.parseInt(stack.pop());
int dig1=Integer.parseInt(stack.pop());
switch(s){
case "+":
stack.push(""+(dig1+dig2));
break;
case "-":
stack.push(""+(dig1-dig2));
break;
case "*":
stack.push(""+(dig1*dig2));
break;
case "/":
stack.push(""+(dig1/dig2));
break;
}
} else {
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}
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
思路:就是用栈来实现后缀式也就是逆波兰式的计算过程
代码如下(已通过leetcode)
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack<String>();
for(String s:tokens) {
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) {
int dig2=Integer.parseInt(stack.pop());
int dig1=Integer.parseInt(stack.pop());
switch(s){
case "+":
stack.push(""+(dig1+dig2));
break;
case "-":
stack.push(""+(dig1-dig2));
break;
case "*":
stack.push(""+(dig1*dig2));
break;
case "/":
stack.push(""+(dig1/dig2));
break;
}
} else {
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}
相关文章推荐
- LeetCode *** 150. Evaluate Reverse Polish Notation
- Lua核心编程之进阶&总结
- 快速掌握Lua 5.3 —— 编写提供给Lua使用的C库函数的技巧 (2)
- lua 元方法
- Lua核心编程之基础
- lua 元表与元方法
- Lua_第23章 C API 纵览
- lua中的string库
- Lua速成
- tolua++没法用
- tolua++没法用
- 轻量级Lua IDE ZeroBrane Studio 的使用技巧和汉化
- Lua 表达式
- Lua学习小记
- lua 点号"."和冒号":"、"seif"使用及区别
- Lua 类型和值
- lua5.2之后返回table长度
- lua运行优点
- Lua 词法约定
- Lua 编程