permutations of a string using iteration

Viewed 30843

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 iterative solution is really not working out. Below I have attached my code. I would really appreciate the help:

public static void combString(String s) {
    char[] a = new char[s.length()];
    //String temp = "";
    for(int i = 0; i < s.length(); i++) {
        a[i] = s.charAt(i);
    }
    for(int i = 0; i < s.length(); i++) {
        String temp = "" + a[i];    

        for(int j = 0; j < s.length();j++) {
            //int k = j;
            if(i != j) {
                System.out.println(j);
                temp += s.substring(0,j) + s.substring(j+1,s.length());
            }               
        }
        System.out.println(temp);
    }
}
7 Answers

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<String> 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<String> 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);
    }
}
package vishal villa;

import java.util.Scanner;

public class Permutation {
    static void result( String st, String ans)
    {

        if(st.length() == 0)
            System.out.println(ans +" ");

        for(int i = 0; i<st.length(); i++)
        {
            char ch = st.charAt(i);
            String r = st.substring(0, i) +  st.substring(i + 1);
            result(r, ans + ch);    
        }   
    }
    public static void main(String[] args) 
    {
        Scanner Sc = new Scanner(System.in);
        System.out.println("enter the string");
        String st = Sc.nextLine();
    Permutation p = new Permutation();
        p.result(st,"" );
    }
}
Related