Search code examples
javaalgorithmoptimizationinfix-notation

Reverse Polish to Infix Notation optimization in java


I am trying to solve a programming challange that involves converting reverse polish notation to infix notation. For example: 1 3 + 2 4 5 - + / would be: ((1+3)/(2+(4-5))) My solution so far does work, but it's not fast enough. So i am looking for any optimization advice.

public class betteralgo {
    public static void main(String[] args) throws IOException {
        BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
        String line = bi.readLine();
        String[] input = line.split(" ");
        StringBuilder builder = new StringBuilder();
        Stack<String> stack = new Stack<String>();

        for(String e:input) {
            switch(e){
                case("+"):
                case("-"):
                case("*"):
                case("/"):
                    String i = stack.pop();
                String k = stack.pop();
                stack.push("(" + k + e + i + ")");
                break;
                default:
                    stack.push(e);
                }
            }
        System.out.println(stack.pop());        
        }       
    }

Solution

  • Your problem is the quadratic complexity due to working with longer and longer expressions. The solution is to build a tree. Instead of

    "(" + k + e + i + ")"
    

    create a new Node with content e and children k and i. Then a simple pass through the tree allows you to generate any representation (infix, prefix or postfix).