在括号中使用Java中的堆栈在括号中创建括号

时间:2019-02-03 20:04:09

标签: java

我需要编写一个Java程序,该程序从标准输入中获取有效的右括号中缀表达式(RPIE),并输出等效的全括号中缀表达式(FPIE)。例如,如果输入为:a + 20)/ bc) 53.4-d))),则输出应为((a + 20)/(((bc)(53.4-d))) )。

我尝试实现以下方法,但未解决。有人可以帮我吗?

import java.util.Scanner;
import java.util.Stack;

public class ParenthesisCreator {

    static private String expression;
    private Stack<Character> stack = new Stack<Character>();

    public ParenthesisCreator(String input) {
        expression = input;
    }

    public String rtParenthesisInfixToFullParenthesis() {
        String postfixString = "";

        for (int index = 0; index < expression.length(); ++index) {
            char value = expression.charAt(index);
            if (value == ')') {
                stack.push(')'); 
                stack.push('(');
                Character oper = stack.peek();
                while (!stack.isEmpty()) {
                    stack.pop();
                    postfixString += oper.charValue();
                    if (!stack.isEmpty())                 
                        oper = stack.peek(); 
                }
            } else {
                postfixString += value;
            }
        }

        return postfixString;
    }


    public static void main(String[] args) {
        System.out.println("Type an expression written in right parenthesized infix: ");
        Scanner input = new Scanner(System.in);
        String expression = input.next();
        // Input: a+20)/b-c)*53.4-d)))
        // Desired output is: ((a+20)/((b-c)*(53.4-d)))
        ParenthesisCreator convert = new ParenthesisCreator(expression);
        System.out.println("This expression writtien in full parenthesized is: \n" + convert.rtParenthesisInfixToFullParenthesis());
    }

}

2 个答案:

答案 0 :(得分:0)

var dynvar = new T[] { initialVal };
var dynref = Expression.Constant(dynvar);

演示

public final class ParenthesisCreator implements Function<String, String> {
    private final IntPredicate isOperator;

    public ParenthesisCreator() {
        this(ch -> ch == '/' || ch == '*' || ch == '+' || ch == '-');
    }

    public ParenthesisCreator(IntPredicate isOperator) {
        this.isOperator = isOperator;
    }

    @Override
    public String apply(String expr) {
        Deque<String> stack = new LinkedList<>();
        StringBuilder buf = null;

        for (int i = 0; i < expr.length(); i++) {
            char ch = expr.charAt(i);

            if (ch == ')') {
                if (buf != null) {
                    stack.push(buf.insert(0, '(').append(')').toString());
                    buf = null;
                } else if (stack.size() >= 2) {
                    String two = stack.pop();
                    String one = stack.pop();
                    stack.push('(' + one + two + ')');
                } else
                    throw new IllegalArgumentException();
            } else if (isOperator.test(ch) && buf == null && !stack.isEmpty())
                stack.push(stack.pop() + ch);
            else
                (buf = buf == null ? new StringBuilder() : buf).append(ch);
        }

        return String.join("", stack);
    }
}

答案 1 :(得分:0)

public class FixExpressionParentheses {

    public String fixExpression(String expression) {
        String[] tokenArray = expression.split(" ");

        Stack<String> operators = new Stack<>();
        Stack<String> operands = new Stack<>();

        for (String token: tokenArray) {
            switch (token) {
                case "+", "-", "*", "/", "sqrt" -> operators.push(token);
                case ")" -> {
                    String operator = operators.pop();
                    String operandTwo = operands.pop();
                    String operandOne = operands.pop();
                    String newToken = "( " + operandOne + " " + operator + " "
                                           + operandTwo + " )";
                    operands.push(newToken);
                }
                default -> operands.push(token);
            }
        }

        return operands.pop();
    }
}