Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)
Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given a Prefix expression, convert it into a Infix expression.
分析:
1 class Solution { 2 boolean isOperator(char x) { 3 switch (x) { 4 case ‘+‘: 5 case ‘-‘: 6 case ‘/‘: 7 case ‘*‘: 8 return true; 9 default: 10 return false; 11 } 12 } 13 14 String preToInfix(String pre_exp) { 15 Stack<String> stack = new Stack<>(); 16 int length = pre_exp.length(); 17 for (int i = length - 1; i >= 0; i--) { 18 if (isOperator(pre_exp.charAt(i))) { 19 String op1 = stack.pop(); 20 String op2 = stack.pop(); 21 22 String temp = "(" + op1 + pre_exp.charAt(i) + op2 + ")"; 23 stack.push(temp); 24 } else { 25 stack.push(pre_exp.charAt(i) + ""); 26 } 27 } 28 return stack.peek(); 29 } 30 }
原文:https://www.cnblogs.com/beiyeqingteng/p/11318704.html