In: Computer Science
IN JAVA
If a list is received for which the last String is in the word list, this method should recursively call itself on a list consisting of all but the last word. If the recursive call returns a String (not null), add the last word back to the end of the String and return it. This method should not contain any loops.
Answer of the first part
Save the program in file Main.java
import java.util.HashSet;
import java.util.Set;
public class Main {
// function to create permutation of the given string
public static Set<String> generate_permutation(String
inputStr){
Set<String> set = new HashSet<String>();
if (inputStr.length() == 0)
return set;
Character chr = inputStr.charAt(0);
if (inputStr.length() > 1) {
inputStr = inputStr.substring(1);
Set<String> pSet = generate_permutation(inputStr);
for (String x : pSet) {
for (int i = 0; i <= x.length(); i++) {
set.add(x.substring(0, i) + chr + x.substring(i));
}
}
} else {
set.add(chr + "");
}
return set;
}
// The main function
public static void main(String[] args) {
System.out.println(generate_permutation("abc"));
}
}
Compile the file as
$javac Main.java
Execute the file as
java Main
to get the output as below
[bca, acb, abc, cba, bac, cab]