w3resource
Java Programming Exercies

Java String Exercises: Print all permutations of a specified string with repetition

Java String: Exercise-35 with Solution

Write a Java program to print all permutations of a given string with repetition.

Pictorial Presentation:

Java String Exercises: Print all permutations of a specified string with repetition

Sample Solution:

Java Code:

import java.util.*;
public class Main {

 public static void main(String[] args) {
  permutationWithRepeation("PQR");

 }

 private static void permutationWithRepeation(String str1) {
  System.out.println("The given string is: PQR");
  System.out.println("The permuted strings are:");
  showPermutation(str1, "");
 }

 private static void showPermutation(String str1, String NewStringToPrint) {

  if (NewStringToPrint.length() == str1.length()) {
   System.out.println(NewStringToPrint);
   return;
  }
  for (int i = 0; i < str1.length(); i++) {

   showPermutation(str1, NewStringToPrint + str1.charAt(i));
  }
 }
}

Sample Output:

The given string is: PQR
The permuted strings are:
PPP
PPQ
PPR
PQP
PQQ
PQR
PRP
PRQ
PRR
QPP
QPQ
QPR
QQP
QQQ
QQR
QRP
QRQ
QRR
RPP
RPQ
RPR
RQP
RQQ
RQR
RRP
RRQ
RRR

Flowchart:

Flowchart: Java String Exercises - Print all permutations of a specified string with repetition

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find the second most frequent character in a given string.
Next: Write a Java program to check whether two strings are interliving of a given string. Assuming that the unique characters in both strings.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming