|
| 1 | +package com.thealgorithms.stacks; |
| 2 | + |
| 3 | +import java.util.Set; |
| 4 | +import java.util.Stack; |
| 5 | + |
| 6 | +/** |
| 7 | + * Evaluate a prefix (Polish) expression using a stack. |
| 8 | + * |
| 9 | + * <p>Example: Expression "+ * 2 3 4" results in 10. |
| 10 | + * <p>Applications: Useful for implementing compilers and interpreters. |
| 11 | + * |
| 12 | + * @author Hardvan |
| 13 | + */ |
| 14 | +public final class PrefixEvaluator { |
| 15 | + private PrefixEvaluator() { |
| 16 | + } |
| 17 | + |
| 18 | + private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/"); |
| 19 | + |
| 20 | + /** |
| 21 | + * Evaluates the given prefix expression and returns the result. |
| 22 | + * |
| 23 | + * @param expression The prefix expression as a string with operands and operators separated by spaces. |
| 24 | + * @return The result of evaluating the prefix expression. |
| 25 | + * @throws IllegalArgumentException if the expression is invalid. |
| 26 | + */ |
| 27 | + public static int evaluatePrefix(String expression) { |
| 28 | + Stack<Integer> stack = new Stack<>(); |
| 29 | + String[] tokens = expression.split("\\s+"); |
| 30 | + |
| 31 | + for (int i = tokens.length - 1; i >= 0; i--) { |
| 32 | + String token = tokens[i]; |
| 33 | + if (isOperator(token)) { |
| 34 | + int operand1 = stack.pop(); |
| 35 | + int operand2 = stack.pop(); |
| 36 | + stack.push(applyOperator(token, operand1, operand2)); |
| 37 | + } else { |
| 38 | + stack.push(Integer.valueOf(token)); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if (stack.size() != 1) { |
| 43 | + throw new IllegalArgumentException("Invalid expression"); |
| 44 | + } |
| 45 | + |
| 46 | + return stack.pop(); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Checks if the given token is an operator. |
| 51 | + * |
| 52 | + * @param token The token to check. |
| 53 | + * @return true if the token is an operator, false otherwise. |
| 54 | + */ |
| 55 | + private static boolean isOperator(String token) { |
| 56 | + return OPERATORS.contains(token); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Applies the given operator to the two operands. |
| 61 | + * |
| 62 | + * @param operator The operator to apply. |
| 63 | + * @param a The first operand. |
| 64 | + * @param b The second operand. |
| 65 | + * @return The result of applying the operator to the operands. |
| 66 | + */ |
| 67 | + private static int applyOperator(String operator, int a, int b) { |
| 68 | + return switch (operator) { |
| 69 | + case "+" -> a + b; |
| 70 | + case "-" -> a - b; |
| 71 | + case "*" -> a * b; |
| 72 | + case "/" -> a / b; |
| 73 | + default -> throw new IllegalArgumentException("Invalid operator"); |
| 74 | + }; |
| 75 | + } |
| 76 | +} |
0 commit comments