Programme Java pour calculer toutes les permutations de la chaîne

Dans cet exemple, nous allons apprendre à calculer toutes les permutations de la chaîne en Java.

Pour comprendre cet exemple, vous devez avoir la connaissance des rubriques de programmation Java suivantes:

  • Chaîne Java
  • Récursivité Java
  • Classe de scanner Java

La permutation de la chaîne signifie toutes les nouvelles chaînes possibles qui peuvent être formées en interchangeant la position des caractères de la chaîne. Par exemple, la chaîne ABC a des permutations (ABC, ACB, BAC, BCA, CAB, CBA) .

Exemple: programme Java pour obtenir toute la permutation d'une chaîne

 import java.util.HashSet; import java.util.Scanner; import java.util.Set; class Main ( public static Set getPermutation(String str) ( // create a set to avoid duplicate permutation Set permutations = new HashSet(); // check if string is null if (str == null) ( return null; ) else if (str.length() == 0) ( // terminating condition for recursion permutations.add(""); return permutations; ) // get the first character char first = str.charAt(0); // get the remaining substring String sub = str.substring(1); // make recursive call to getPermutation() Set words = getPermutation(sub); // access each element from words for (String strNew : words) ( for (int i = 0;i<=strNew.length();i++)( // insert the permutation to the set permutations.add(strNew.substring(0, i) + first + strNew.substring(i)); ) ) return permutations; ) public static void main(String() args) ( // create an object of scanner class Scanner input = new Scanner(System.in); // take input from users System.out.print("Enter the string: "); String data = input.nextLine(); System.out.println("Permutations of " + data + ": " + getPermutation(data)); ) )

Production

 Entrez la chaîne: ABC Permutations de ABC: (ACB, BCA, ABC, CBA, BAC, CAB)

En Java, nous avons utilisé la récursivité pour calculer toutes les permutations d'une chaîne. Ici, nous stockons la permutation dans un ensemble. Donc, il n'y aura pas de permutation en double.

Articles intéressants...