150. Evaluate Reverse Polish Notation
2017-03-15 18:36
330 查看
Evaluate the value of anarithmetic 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
翻译:
在逆向波兰记法中评估算术表达式的值。有效运算符为+, -
,*,/。每个操作数可以是整数或另一个表达式。
题目就是栈那一节的表达式求值,但是它稍微简单一点。没有括号,不用考虑符号的优先级别。还有注意一点的就是,LeetCode的jdk是1.7以下,所以不支持switch表达式是字符串。代码如下:
public class Solution {
public int evalRPN(String[] tokens) {
String op="+-*/";
Stack<String> stack=new Stack();
for(String s: tokens){
if(op.contains(s)){
int a=Integer.valueOf(stack.pop());
int b=Integer.valueOf(stack.pop());
int index=op.indexOf(s);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}else{
stack.push(s);
}
}
return Integer.valueOf(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的jdk是1.7以下,所以不支持switch表达式是字符串。代码如下:
public class Solution {
public int evalRPN(String[] tokens) {
String op="+-*/";
Stack<String> stack=new Stack();
for(String s: tokens){
if(op.contains(s)){
int a=Integer.valueOf(stack.pop());
int b=Integer.valueOf(stack.pop());
int index=op.indexOf(s);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}else{
stack.push(s);
}
}
return Integer.valueOf(stack.pop());
}
}
相关文章推荐
- 150. Evaluate Reverse Polish Notation
- leetcode 150.Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- leetcode-150. Evaluate Reverse Polish Notation
- [LeetCode]150.Evaluate Reverse Polish Notation
- leecode 解题总结:150. Evaluate Reverse Polish Notation
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- Middle-题目102:150. Evaluate Reverse Polish Notation
- Leetcode 150. Evaluate Reverse Polish Notation (Medium) (cpp)
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation**
- 150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- leetcode 150. Evaluate Reverse Polish Notation
- Stack-----150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation(计算后缀表达式)
- 150. Evaluate Reverse Polish Notation