permutations of a string using iteration

前端 未结 7 1848
迷失自我
迷失自我 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:57

    Just posting my approach to the problem:

    import java.util.ArrayDeque;
    import java.util.Queue;
    
    public class PermutationIterative {
        public static void main(String[] args) {
            permutationIterative("abcd");
        }
    
        private static void permutationIterative(String str) {
            Queue currentQueue = null;
            int charNumber = 1;
            for (char c : str.toCharArray()) {
                if (currentQueue == null) {
                    currentQueue = new ArrayDeque<>(1);
                    currentQueue.add(String.valueOf(c));
                } else {
                    int currentQueueSize = currentQueue.size();
                    int numElements = currentQueueSize * charNumber;
                    Queue nextQueue = new ArrayDeque<>(numElements);
                    for (int i = 0; i < currentQueueSize; i++) {
                        String tempString = currentQueue.remove();
                        for (int j = 0; j < charNumber; j++) {
                            int n = tempString.length();
                            nextQueue.add(tempString.substring(0, j) + c + tempString.substring(j, n));
                        }
                    }
                    currentQueue = nextQueue;
                }
                charNumber++;
            }
            System.out.println(currentQueue);
        }
    }
    

提交回复
热议问题