1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public int evalRPN(String[] tokens) { Stack<Integer> numStack = new Stack<>(); for (String token : tokens) { switch (token) { case "+": { numStack.push(numStack.pop() + numStack.pop()); break; } case "-": { int b = numStack.pop(), a = numStack.pop(); numStack.push(a - b); break; } case "*": { numStack.push(numStack.pop() * numStack.pop()); break; } case "/": { int b = numStack.pop(), a = numStack.pop(); numStack.push(a / b); break; } default: numStack.push(Integer.parseInt(token)); } }
return numStack.pop(); } }
|
References
150. Evaluate Reverse Polish Notation
剑指 Offer II 036. 后缀表达式