LeetCode–Evaluate Reverse Polish Notation
(LeetCode - 评价逆波兰表示法,即后缀表达式)
By X Wang
(LeetCode: 一个在线编程网站,里面有很多大公司面试的题目)
The problem:
问题
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
1. Naive Approach 朴素(简单)方法
This problem is simple. After understanding the problem, we should quickly realize that this problem can be solved by using a stack. We can loop through each element in the given array. When it is a number, push it to the stack. When it is an operator, pop two numbers from the stack, do the calculation, and push back the result.
这是一个简单的问题,在理解这个问题之后,我们应该很快意识到这个问题能用栈来解决。我们依次处理给定数组里的每个元素,当它是一个数字时,压入栈中;当它是一个操作符时,从栈中弹出两个数进行运算,并且将运算结果压入栈中。
The following is the code. It runs great by feeding a small test. However, this code contains compilation errors in leetcode. Why?
以下是代码。通过一个小测试可知运行良好,然而,这份代码在LeetCode上却有编译错误,是为什么?
public class Test {
public static void main(String[] args) throws IOException { String[] tokens = new String[] { "2", "1", "+", "3", "*" }; System.out.println(evalRPN(tokens)); }
public static int evalRPN(String[] tokens) { int returnValue = 0; String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for (String t : tokens) { if (!operators.contains(t)) { stack.push(t); } else { int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); switch (t) { case "+": stack.push(String.valueOf(a + b)); break; case "-": stack.push(String.valueOf(b - a)); break; case "*": stack.push(String.valueOf(a * b)); break; case "/": stack.push(String.valueOf(b / a)); break; } } }
returnValue = Integer.valueOf(stack.pop());
return returnValue; } } |
The problem is that switch string statement is only available from JDK 1.7. LeetCode apparently use versions below that.
这个问题是因为在switch里声明string只能在JDK 1.7里,而LeetCode显然地使用是更低版本的。
2. Accepted Solution 可接受的解决方案
If you want to use switch statement, you can convert the above by using the following code which use the index of a string “+-*/”.
如果你想使用switch,你可以使用以下的代码代替上面的,下面的代码在switch里声明的是字符串“+-*/”的下标。
public class Solution { public int evalRPN(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for(String t : tokens){ if(!operators.contains(t)){ stack.push(t); } else{ int a =Integer.valueOf(stack.pop()); int b =Integer.valueOf(stack.pop()); int index = operators.indexOf(t); 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; } } } returnValue =Integer.valueOf(stack.pop()); return returnValue; } }
|
|