Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.
Input : abc++ Output : (a + (b + c)) Input : ab*c+ Output : ((a*b)+c)
分析
1. Read the next symbol from the input.
2.If the symbol is an operand, push it onto the stack.
3.Otherwise,
…3.1 the symbol is an operator.
…3.2 Pop the top 2 values from the stack.
…3.3 Put the operator, with the values as arguments and form a string.
…3.4 Push the resulted string back to stack.
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 postToInfix(String exp) { 15 Stack<String> s = new Stack<String>(); 16 17 for (int i = 0; i < exp.length(); i++) { 18 if (!isOperator(exp.charAt(i))) { 19 s.push(exp.charAt(i) + ""); 20 } else { 21 String op1 = s.pop(); 22 String op2 = s.pop(); 23 s.push("(" + op2 + exp.charAt(i) + op1 + ")"); 24 } 25 } 26 return s.peek(); 27 } 28 }
原文:https://www.cnblogs.com/beiyeqingteng/p/11318722.html