IN JAVA: Write a recursive method to print all the permutations of any string. F
ID: 3736259 • Letter: I
Question
IN JAVA:
Write a recursive method to print all the permutations of any string. For example, for the string abc:
abc
acb
bac
bca
cab
cba
using following two methods:
public static void displayPermutations (String s)
public static void displayPermutations (String s1, String s2) //helper
Note: Helper method, uses a loop to move a character from s2 to s1 and recursively invokes it with a new s1 and s2. The base case is that s2 is empty and print s1 to the console.
Here is the given code with a Driver Class, DO NOT MODIFY THE CODE
import java.util.*;
import java.lang.*;
import java.io.*;
class HW4_P1{
public static void displayPermuation(String s) {
displayPermutation("",s);
}
public static void displayPermuation(String s1, String s2) {
}
}
class DriverMain{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
HW4_P1.displayPermuation(input.nextLine());
}
}
Explanation / Answer
Java program to print all the permutations of any string.by using two methods.
import java.util.*;
import java.lang.*;
import java.io.*;
class HW4_P1
{
public static void displayPermutation(String s)
{
displayPermutation(" ",s);
}
public static void displayPermutation(String s1, String s2)
{
int n = s2.length();
if (n == 0)
System.out.println(s1);
else
{
for (int i = 0; i < n; i++)
displayPermutation(s1 + s2.charAt(i), s2.substring(0, i) + s2.substring(i+1, n));
}
}
}
class DriverMain
{
public static void main(String args[])
{
System.out.println("Please enter the String :");
Scanner input = new Scanner(System.in);
HW4_P1.displayPermutation(input.nextLine());
}
}
Sample Output:
javac DriverMain.java
java DriverMain
Please enter the String :
ABC
ABC
ACB
BAC
BCA
CAB
CBA