LeetCode – Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. For example:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
1. Naive Approach
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. However, this code contains compilation errors in leetcode. Why?
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)) { //push to stack if it is a number stack.push(t); } else {//pop numbers from stack if it is an operator 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 a JDK version below 1.7.
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 "+-*/".
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; } } |
<pre><code> String foo = "bar"; </code></pre>
-
Rajeev J
-
Cat Racket
-
Ehsun Behravesh
-
PraveenKumar Subramanian
-
sam
-
ANAND
-
Brikesh Kumar
-
LegoMushroom
-
emirpolo
-
Greg Mueller
-
bimal prasad pandey
-
Ryan Shaw
-
Abhishek Roy
-
srj_michael
-
srj_michael
-
Yunxiao Zou
-
Taylor Annaterre
-
meha
-
Parag Chaudhari
-
anonymous
-
cg22165
-
sebastian
-
ryanlr
-
Salil Surendran
-
sola
-
Julien Dreux
-
themansitiwari
-
Dongyon Kang
-
Axel Hadfeg
-
codingfacts
-
Henco Appel
-
Henco Appel
-
shreyas KN
-
ryanlr
-
JeffreyT