- 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.
- class Solution {
- boolean isOperator(char x) {
- switch (x) {
- case '+':
- case '-':
- case '/':
- case '*':
- return true;
- default:
- return false;
- }
- }
- String postToInfix(String exp) {
- Stack<String> s = new Stack<String>();
- for (int i = 0; i < exp.length(); i++) {
- if (!isOperator(exp.charAt(i))) {
- s.push(exp.charAt(i) + "");
- } else {
- String op1 = s.pop();
- String op2 = s.pop();
- s.push("(" + op2 + exp.charAt(i) + op1 + ")");
- }
- }
- return s.peek();
- }
- }
来源: http://www.bubuko.com/infodetail-3147797.html