|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/evaluate-reverse-polish-notation |
| 6 | +class EvaluateReversePolishNotation { |
| 7 | + private final Set<String> OPERATORS = Set.of("+", "-", "*", "/"); |
| 8 | + |
| 9 | + // Stack |
| 10 | + // O(n) time, O(n) space |
| 11 | + public int evalRPN(String[] tokens) { |
| 12 | + Stack<Integer> stack = new Stack<>(); |
| 13 | + for (String token : tokens) { |
| 14 | + if (OPERATORS.contains(token)) { |
| 15 | + int num2 = stack.pop(); |
| 16 | + int num1 = stack.pop(); |
| 17 | + int result = calculate(num1, num2, token); |
| 18 | + stack.add(result); |
| 19 | + } else { |
| 20 | + stack.add(Integer.parseInt(token)); |
| 21 | + } |
| 22 | + } |
| 23 | + return stack.pop(); |
| 24 | + } |
| 25 | + |
| 26 | + private int calculate(int num1, int num2, String operator) { |
| 27 | + if ("+".equals(operator)) { |
| 28 | + return num1 + num2; |
| 29 | + } else if ("-".equals(operator)) { |
| 30 | + return num1 - num2; |
| 31 | + } else if ("*".equals(operator)) { |
| 32 | + return num1 * num2; |
| 33 | + } else { |
| 34 | + return num1 / num2; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Test |
| 39 | + public static void main(String[] args) { |
| 40 | + EvaluateReversePolishNotation solution = new EvaluateReversePolishNotation(); |
| 41 | + |
| 42 | + String[] input1 = {"2", "1", "+", "3", "*"}; |
| 43 | + int expectedOutput1 = 9; |
| 44 | + int actualOutput1 = solution.evalRPN(input1); |
| 45 | + System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1)); |
| 46 | + |
| 47 | + String[] input2 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}; |
| 48 | + int expectedOutput2 = 22; |
| 49 | + int actualOutput2 = solution.evalRPN(input2); |
| 50 | + System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2)); |
| 51 | + } |
| 52 | +} |
0 commit comments