1.

How to print all permutations of string in Java?

Answer»

The TERM "permutation of the string" refers to all of the conceivable new strings that can be created by swapping the positions of the given string's characters. For example, the string CAT has a total of 6 permutations i.e., [CAT, CTA, ACT, ATC, TCA, TAC]. Below is a JAVA program to print all permutations of a given string.

public class InterviewBit { // Function to display all permutations of the string str static void printallPermutns(String str, String str2) { // check if string is empty or NULL if (str.length() == 0) { System.out.print(str2 + " "); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String str3 = str.substring(0, i) + str.substring(i + 1); // Recursive CALL printallPermutns(str3, str2 + ch); } } // Driver CODE public static void main(String[] args) { String s = "cat"; printallPermutns(s, ""); }}

Output: 

cat cta act atc tca tac


Discussion

No Comment Found