In this tutorial, we will see “How to Print all Permutations of a String in Java”
Print all permutations of string in java
Java – How to Print all Permutations of a String? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /** * Print All Permutations of String in Java * @author Deepak Verma */ import java.util.Scanner; public class Print_All_Permutations_Of_String_Java { public static void main(String[] args) { try (var scan = new Scanner(System.in)) { System.out.println("Enter the string to Permute: "); String str = scan.nextLine(); int n = str.length(); permuteString(str, 0, n - 1); } } public static void permuteString(String str, int l, int r) { if (l == r) { System.out.println(str); } else { for (int i = l; i <= r; i++) { str = swapChar(str, l, i); permuteString(str, l + 1, r); str = swapChar(str, l, i); } } } public static String swapChar(String str, int i, int j) { char[] charArray = str.toCharArray(); char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Enter the string to Permute: Tech Tech Tehc Tceh Tche Thce Thec eTch eThc ecTh echT ehcT ehTc ceTh cehT cTeh cThe chTe cheT hecT heTc hceT hcTe hTce hTec |
check if text or string present in a file using java 8
Print all permutations of string in java
Java – How to Print all Permutations of a String? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: