Write a recursive method that will find and list all of the one-element sequence
ID: 3671835 • Letter: W
Question
Write a recursive method that will find and list all of the one-element sequences of a letters in a char [] array, then all the two-element sequences, then all of the three element sequences, and so on, such that the characters in each sequence appear in the same order as they are in the array. For example, for the following array: char[] letters = {'A', 'C', 'E', 'G'}; the one-element sequences are "A", "C", "E", and "G" the two-element sequences are "AC", "AE", "AG", "CE", "CG", "EG" the three-element sequences are "ACE", "ACG", "AEG", "CEG" the four-element sequence is "ACEG"Explanation / Answer
package com.jd.first;
import java.util.HashSet;
import java.util.Set;
/**
* Java Program to find all permutations of a String
* @author pankaj
*
*/
public class StringHelper {
public static Set<String> permutationFinder(String str) {
Set<String> perm = new HashSet<String>();
//Handling error scenarios
if (str == null) {
return null;
} else if (str.length() == 0) {
perm.add("");
return perm;
}
char initial = str.charAt(0); // first character
String rem = str.substring(1); // Full string without first character
Set<String> words = permutationFinder(rem);
for (String strNew : words) {
for (int i = 0;i<=strNew.length();i++){
perm.add(charInsert(strNew, initial, i));
}
}
return perm;
}
public static String charInsert(String str, char c, int j) {
String begin = str.substring(0, j);
String end = str.substring(j);
return begin + c + end;
}
public static void main(String[] args) {
String s = "AAC";
String s1 = "ABC";
String s2 = "ABCD";
System.out.println(" Permutations for " + s + " are: " + permutationFinder(s));
System.out.println(" Permutations for " + s1 + " are: " + permutationFinder(s1));
System.out.println(" Permutations for " + s2 + " are: " + permutationFinder(s2));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.