|
1 | 1 | class Solution {
|
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)); |
| 2 | + |
| 3 | + private static final Set<String> OPERATIONS = Set.of("*", "+", "/", "-"); |
| 4 | + |
| 5 | + public int evalRPN(String[] tokens) { |
| 6 | + Stack<Integer> stack = new Stack<>(); |
| 7 | + for (String token : tokens) { |
| 8 | + if (OPERATIONS.contains(token)) { |
| 9 | + stack.push(performOperation(stack.pop(), stack.pop(), token)); |
| 10 | + } else { |
| 11 | + stack.push(Integer.parseInt(token)); |
| 12 | + } |
| 13 | + } |
| 14 | + return stack.pop(); |
9 | 15 | }
|
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; |
| 16 | + |
| 17 | + private static int performOperation(int num2, int num1, String operation) throws UnsupportedOperationException { |
| 18 | + return switch(operation) { |
| 19 | + case "+" -> num1 + num2; |
| 20 | + case "-" -> num1 - num2; |
| 21 | + case "*" -> num1 * num2; |
| 22 | + case "/" -> num1 / num2; |
| 23 | + default -> throw new UnsupportedOperationException("Operation not supported"); |
| 24 | + }; |
25 | 25 | }
|
26 |
| - } |
27 | 26 | }
|
0 commit comments