English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à calculer toutes les permutations de la chaîne dans Java.
Pour comprendre cet exemple, vous devriez comprendre les éléments suivantsProgrammation JavaSujet :
La permutation de la chaîne est l'ensemble de toutes les nouvelles chaînes possibles formées par l'échange des positions des caractères de la chaîne. Par exemple, la chaîne ABC combinations disponibles [ABC, ACB, BAC, BCA, CAB, CBA].
import java.util.HashSet; import java.util.Scanner; import java.util.Set; class Main { public static Set<String> getPermutation(String str) { //Créer une collection set pour éviter les répétitions des alignements Set<String> permutations = new HashSet<String>(); //Vérifier si la chaîne est vide if (str == null) { return null; } else if (str.length() == 0) { //Condition de terminaison récursive permutations.add(""); return permutations; } //Obtenir le premier caractère char first = str.charAt(0); //Obtenir la sous-chaine restante String sub = str.substring(1); //Appel récursif de getPermutation() Set<String> words = getPermutation(sub); //Parcourir words for (String strNew : words) { for (int i = 0; i <= strNew.length(); i++{ //Insérer l'alignement dans la collection set permutations.add(strNew.substring(0, i)) + first + strNew.substring(i)); } } return permutations; } public static void main(String[] args) { //Create an object of the Scanner class Scanner input = new Scanner(System.in); // Accept user input System.out.print("Input string: \t"); String data = input.nextLine(); System.out.println(data + "\t\t" permutations are: \n" + getPermutation(data)); } }
Output result
Input string: ABC The permutations of ABC are: [ACB, BCA, ABC, CBA, BAC, CAB]
In Java, we use recursion to calculate all permutations of a string. Here, we store the permutations in a set collection. Therefore, there will be no duplicate permutations.