Program Java pro výpočet všech permutací řetězce

V tomto příkladu se naučíme vypočítat všechny permutace řetězce v Javě.

Abychom porozuměli tomuto příkladu, měli byste znát následující programovací témata Java:

  • Řetězec Java
  • Java rekurze
  • Třída skeneru Java

Permutací řetězce se rozumí všechny možné nové řetězce, které mohou být vytvořeny záměnou polohy znaků řetězce. Například řetězec ABC má permutace (ABC, ACB, BAC, BCA, CAB, CBA) .

Příklad: Program Java pro získání veškeré permutace řetězce

 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)); ) )

Výstup

 Zadejte řetězec: ABC Permutace ABC: (ACB, BCA, ABC, CBA, BAC, CAB)

V Javě jsme použili rekurzi k výpočtu všech permutací řetězce. Zde ukládáme permutaci do sady. Duplicitní permutace tedy nebude existovat.

Zajímavé články...