Write a Java Program to get all the permutation of a string

Java program to get the all permutation of a string :

In this tutorial, we will learn how to print all the permutation of a string . We are going to use recursive approach to print all the permutations.

Java Program :

import java.util.Scanner;

public class Main {
    /**
     * Utility function to print
     */
    private static void println(String str) {
        System.out.println(str);
    }

    private static void print(String str) {
        System.out.print(str);
    }


    public static String swapCharacters(String string, int i, int j)
    {
        char tempCharacter;
        char[] charArray = string.toCharArray();
        tempCharacter = charArray[i] ;
        charArray[i] = charArray[j];
        charArray[j] = tempCharacter;

        return String.valueOf(charArray);
    }

    private static void findPermutation(String inputString,int leftIndex,int sizeOfString){

        if(leftIndex == sizeOfString){
            print(inputString+" ");
        }else{
            for(int i = leftIndex;i<sizeOfString;i++){
                inputString = swapCharacters(inputString,leftIndex,i);
                findPermutation(inputString,leftIndex+1,sizeOfString);
                inputString = swapCharacters(inputString,leftIndex,i);
            }
        }
    }

    public static void main(String[] args) throws java.lang.Exception {

        String userInputString ;
        Scanner scanner = new Scanner(System.in);

        println("Enter a string : ");
        userInputString = scanner.next();

       findPermutation(userInputString,0,userInputString.length());
    }

}

Sample Output:

Enter a string : 
abc
abc acb bac bca cba cab 

Enter a string : 
abcd
abcd abdc acbd acdb adcb adbc bacd badc bcad bcda bdca bdac cbad cbda cabd cadb cdab cdba dbca dbac dcba dcab dacb dabc 
Sitewide-USD 336x280

Leave a Reply