package com.thealgorithms.datastructures.stacks;
import java.util.Stack;
public class PostfixToInfix {
public static boolean isOperator(char token) {
switch (token) {
case '+':
case '-':
case '/':
case '*':
case '^':
return true;
}
return false;
}
public static boolean isValidPostfixExpression(String postfix) {
if (postfix.length() < 3) return false;
if (isOperator(postfix.charAt(0))) return false;
if (isOperator(postfix.charAt(1))) return false;
int operandCount = 0;
int operatorCount = 0;
for (int i = 0; i < postfix.length(); i++) {
char token = postfix.charAt(i);
if (isOperator(token)) {
operatorCount++;
if (operatorCount >= operandCount) return false;
} else {
if (operatorCount == 0) {
operandCount++;
continue;
}
if (operandCount != operatorCount + 1) return false;
operandCount = 2;
operatorCount = 0;
}
}
return (operandCount == operatorCount + 1);
}
public static String getPostfixToInfix(String postfix) {
String infix = "";
if (postfix.isEmpty()) return infix;
if (!isValidPostfixExpression(postfix)) {
throw new IllegalArgumentException("Invalid Postfix Expression");
}
Stack<String> stack = new Stack<>();
StringBuilder valueString = new StringBuilder();
String operandA, operandB;
char operator;
for (int index = 0; index < postfix.length(); index++) {
char token = postfix.charAt(index);
if (!isOperator(token)) {
stack.push(Character.toString(token));
continue;
}
operator = token;
operandB = stack.pop();
operandA = stack.pop();
valueString.append('(');
valueString.append(operandA);
valueString.append(operator);
valueString.append(operandB);
valueString.append(')');
stack.push(valueString.toString());
valueString.setLength(0);
}
infix = stack.pop();
return infix;
}
public static void main(String args[]) {
assert getPostfixToInfix("ABC+/").equals("(A/(B+C))");
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))");
assert getPostfixToInfix("AB+CD^/E*FGH+-^")
.equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
}
}