permutations of a string using iteration

前端 未结 7 1840
迷失自我
迷失自我 2020-12-16 14:36

I\'m trying to find permutation of a given string, but I want to use iteration. The recursive solution I found online and I do understand it, but converting it to an iterati

7条回答
  •  天涯浪人
    2020-12-16 14:54

    Work queue allows us to create an elegant iterative solution for this problem.

    static List permutations(String string) {
        List permutations = new LinkedList<>();
        Deque workQueue = new LinkedList<>(); 
    
        // We need to permutate the whole string and haven't done anything yet.
        workQueue.add(new WorkUnit(string, ""));
    
        while (!workQueue.isEmpty()) { // Do we still have any work?
            WorkUnit work = workQueue.poll();
    
            // Permutate each character.
            for (int i = 0; i < work.todo.length(); i++) {
                String permutation = work.done + work.todo.charAt(i);
    
                // Did we already build a complete permutation?
                if (permutation.length() == string.length()) {
                    permutations.add(permutation);
                } else {
    
                    // Otherwise what characters are left? 
                    String stillTodo = work.todo.substring(0, i) + work.todo.substring(i + 1);
                    workQueue.add(new WorkUnit(stillTodo, permutation));
                }
            }
        }
        return permutations; 
    }
    

    A helper class to hold partial results is very simple.

    /**
     * Immutable unit of work
     */
    class WorkUnit {
        final String todo;
        final String done;
    
        WorkUnit(String todo, String done) {
            this.todo = todo;
            this.done = done;
        }
    }
    

    You can test the above piece of code by wrapping them in this class.

    import java.util.*;
    
    public class AllPermutations {
    
        public static void main(String... args) {
            String str = args[0];
            System.out.println(permutations(str));
        }
    
        static List permutations(String string) {
            ...
        }
    }
    
    class WorkUnit {
        ...
    }
    

    Try it by compiling and running.

    $ javac AllPermutations.java; java AllPermutations abcd
    

    The below implementation can also be easily tweaked to return a list of permutations in reverse order by using a LIFO stack of work instead of a FIFO queue.

提交回复
热议问题