|
1 | 1 | class Solution {
|
2 |
| - public int evalRPN(String[] tokens) { |
3 |
| - Stack<Integer> stack = new Stack<>(); |
4 |
| - Set<String> operations = new HashSet<>(Arrays.asList("-", "+", "*", "/")); |
5 |
| - for (String token : tokens) { |
6 |
| - if (operations.contains(token)) { |
7 |
| - int num1 = stack.pop(); |
8 |
| - int num2 = stack.pop(); |
9 |
| - stack.push(performOperation(num2, num1, token)); |
10 |
| - } |
11 |
| - else { |
12 |
| - stack.push(Integer.parseInt(token)); |
13 |
| - } |
14 |
| - } |
15 |
| - |
16 |
| - return stack.pop(); |
| 2 | + public int evalRPN(String[] tokens) { |
| 3 | + Stack<Integer> stack = new Stack<>(); |
| 4 | + String operations = "+-/*"; |
| 5 | + for (String token : tokens) { |
| 6 | + stack.push(operations.contains(token) ? Objects |
| 7 | + .requireNonNull(performOperation(stack.pop(), stack.pop(), token)) |
| 8 | + : Integer.parseInt(token)); |
17 | 9 | }
|
18 |
| - |
19 |
| - private int performOperation(int a, int b, String operation) { |
20 |
| - switch(operation) { |
21 |
| - case "+": |
22 |
| - return a + b; |
23 |
| - case "-": |
24 |
| - return a - b; |
25 |
| - case "*": |
26 |
| - return a * b; |
27 |
| - default: |
28 |
| - return a / b; |
29 |
| - } |
| 10 | + return stack.pop(); |
| 11 | + } |
| 12 | + |
| 13 | + private Integer performOperation(Integer secondOperand, Integer firstOperand, String operation) { |
| 14 | + switch (operation) { |
| 15 | + case "+": |
| 16 | + return firstOperand + secondOperand; |
| 17 | + case "-": |
| 18 | + return firstOperand - secondOperand; |
| 19 | + case "*": |
| 20 | + return firstOperand * secondOperand; |
| 21 | + case "/": |
| 22 | + return firstOperand / secondOperand; |
| 23 | + default: |
| 24 | + return null; |
30 | 25 | }
|
| 26 | + } |
31 | 27 | }
|
0 commit comments