English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to calculate all permutations and combinations of strings in Java.
To understand this example, you should understand the followingJava programmingTopic:
The permutation of a string refers to all possible new strings that can be formed by interchanging the positions of the characters in the string. For example, the string ABC The permutations and combinations it has [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) { //Create a set collection to avoid duplicate permutations Set<String> permutations = new HashSet<String>() //Check if the string is empty if (str == null) { return null; } else if (str.length() == 0) { //Recursive termination condition permutations.add(""); return permutations; } //Get the first character char first = str.charAt(0); //Get the remaining substring String sub = str.substring(1); //Recursive call to getPermutation() Set<String> words = getPermutation(sub) //Traverse words for (String strNew : words) { for (int i = 0; i <= strNew.length(); i++{ //Insert the permutation into the set collection 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: "); String data = input.nextLine(); System.out.println(data + " "'s permutations are: " + getPermutation(data)); } }
Output result
Input string: ABC Permutations of ABC: [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.