JAVA中缀表达式

JAVA中缀表达式

import java.util.Stack;

public class PrefixExpressionCalculator {

    public static String infixToPrefix(String infixExpression) {
        // 反转输入的中缀表达式
        String reversedInfix = new StringBuilder(infixExpression).reverse().toString();

        StringBuilder prefixExpression = new StringBuilder();
        Stack<Character> operatorStack = new Stack<>();

        for (int i = 0; i < reversedInfix.length(); i++) {
            char currentChar = reversedInfix.charAt(i);

            if (Character.isLetterOrDigit(currentChar)) {
                prefixExpression.append(currentChar);
            } else if (currentChar == ')') {
                operatorStack.push(currentChar);
            } else if (currentChar == '(') {
                while (!operatorStack.isEmpty() && operatorStack.peek() != ')') {
                    prefixExpression.append(operatorStack.pop());
                }
                operatorStack.pop(); // 弹出匹配的 ')'
            } else {
                // 处理运算符
                while (!operatorStack.isEmpty() && getPrecedence(currentChar) < getPrecedence(operatorStack.peek())) {
                    prefixExpression.append(operatorStack.pop());
                }
                operatorStack.push(currentChar);
            }
        }

        // 处理剩余的运算符
        while (!operatorStack.isEmpty()) {
            prefixExpression.append(operatorStack.pop());
        }

        // 反转得到最终的前缀表达式
        return prefixExpression.reverse().toString();
    }

    private static int getPrecedence(char operator) {
        switch (operator) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            default:
                return 0; // 对于其他字符,如括号,优先级设为 0
        }
    }
    public static int evaluatePrefixExpression(String expression) {
        Stack<Integer> stack = new Stack<>();

        // 将表达式拆分为字符数组,逆序入栈
        String[] tokens = expression.split("\\s+");
        for (int i = tokens.length - 1; i >= 0; i--) {
            String token = tokens[i];
            if (isNumeric(token)) {
                stack.push(Integer.parseInt(token));
            } else {
                // 遇到运算符,从栈中弹出两个操作数进行计算,将结果入栈
                int operand1 = stack.pop();
                int operand2 = stack.pop();
                switch (token) {
                    case "+":
                        stack.push(operand1 + operand2);
                        break;
                    case "-":
                        stack.push(operand1 - operand2);
                        break;
                    case "*":
                        stack.push(operand1 * operand2);
                        break;
                    case "/":
                        stack.push(operand1 / operand2);
                        break;
                    // 可以扩展其他运算符
                }
            }
        }

        // 栈顶即为最终结果
        return stack.pop();
    }

    private static boolean isNumeric(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        // 中缀表达式: 2*3/(2-1)+3*(4-1)
        String infixExpression = "1+2+3*0";

        // 转换为前缀表达式
        String prefixExpression = infixToPrefix(infixExpression);
        System.out.println("Prefix Expression: " + prefixExpression);

        String res = addSpaces(prefixExpression);

        // 计算前缀表达式
        int result = evaluatePrefixExpression(res);
        System.out.println("Result: " + result);
    }

    public static String addSpaces(String input) {
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < input.length(); i++) {
            stringBuilder.append(input.charAt(i));
            // 在每个字符之间添加空格,除非是字符串的最后一个字符
            if (i < input.length() - 1) {
                stringBuilder.append(" ");
            }
        }

        return stringBuilder.toString();
    }
}

 

posted @ 2024-01-09 15:38  唐胜伟  阅读(6)  评论(0编辑  收藏  举报