712306. Postfix to Infix Conversion
Medium
Postfix to Infix Conversion
Summary
The problem involves converting a given postfix expression into its equivalent infix notation. Postfix expressions are written in reverse Polish notation, where operators follow their operands. The task is to write an algorithm that takes a postfix expression as input and outputs the corresponding infix expression.
Detailed Explanation
To solve this problem, we can use a stack-based approach. We'll iterate through the postfix expression from left to right, and for each token (operand or operator), we'll apply the following rules:
- If the token is an operand, add it to the output string as is.
- If the token is an operator, pop operands from the stack until you find the matching operator at the top of the stack. Then, add the popped operands and the current operator to the output string.
Here's a step-by-step breakdown:
- Initialize an empty stack
Sand an empty output stringresult. - Iterate through the postfix expression:
- For each token (operand or operator):
- If it's an operand, add it to
result. - If it's an operator, pop operands from
Suntil you find the matching operator at the top ofS. Then, add the popped operands and the current operator toresult.
- If it's an operand, add it to
- For each token (operand or operator):
- Return the final value of
result.
Here's an example:
Postfix expression: A B + C D *
Output: ( A + (B * C) * D )
Optimized Solutions
Java
public class PostfixToInfix {
public static String convert(String postfix) {
Stack<String> stack = new Stack<>();
StringBuilder result = new StringBuilder();
for (String token : postfix.split(" ")) {
if (token.matches("[a-zA-Z]+")) { // operand
result.append(token).append(" ");
} else { // operator
while (!stack.isEmpty() && !isMatchingOperator(stack.peek(), token)) {
result.append(stack.pop()).append(" ");
}
stack.push(token);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop()).append(" ");
}
return result.toString().trim();
}
private static boolean isMatchingOperator(String op1, String op2) {
// implement your matching logic here
// for example:
return op1.equals("(") && op2.equals(")");
}
}