Permutation List given String using Java

In this tutorial, We will show you about How to get Permutation List given string using Java Program. The program has been tested and shared in the same post.

PermutationList.java

package com.dineshkrish;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PermutationList {
// Defining Array List Object to store the permutation string
private static final List<String> permutationList = new ArrayList<String>();
public static void doPermutation(String str) {
doPermutation("", str);
}
private static void doPermutation(String prefix, String str) {
int len = str.length();
if (len == 0) {
permutationList.add(prefix); // Adding the each permutation
}
else {
for (int i = 0; i < len; i++) {
doPermutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, len)); 
}
}
}
public static void main(String[] args) {
// Defining Scanner Object to read string
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the String to find permutation list : ");
String strValue = scanner.next(); // Reading the string input from user to perform permutation
doPermutation(strValue); // Calling permutation method
System.out.println("Permutation Count : "+permutationList.size());
System.out.println("Permutation List : "+permutationList);
}
}

Output

—————-
Enter the String to find permutation list : abc
Permutation Count : 6
Permutation List : [abc, acb, bac, bca, cab, cba]

Reference

Java Permutations

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *