Program Java na výpočet všetkých permutácií reťazca

V tomto príklade sa naučíme vypočítať všetky permutácie reťazca v Jave.

Aby ste pochopili tento príklad, mali by ste mať znalosti nasledujúcich tém programovania v jazyku Java:

  • Java String
  • Java rekurzia
  • Trieda skenerov Java

Permutácia reťazca znamená všetky možné nové reťazce, ktoré je možné vytvoriť zamenením polohy znakov reťazca. Napríklad reťazec ABC má permutácie (ABC, ACB, BAC, BCA, CAB, CBA) .

Príklad: Program Java na získanie celej permutácie reťazca

 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ýkon

 Zadajte reťazec: ABC Permutácie ABC: (ACB, BCA, ABC, CBA, BAC, CAB)

V prostredí Java sme pomocou rekurzie vypočítali všetky permutácie reťazca. Tu ukladáme permutáciu do súpravy. Nebude teda existovať duplicitná permutácia.

Zaujímavé články...