In: Computer Science
Write a static method called generateSubstrings that adds all subsets of the letters in its first argument to the ArrayList that is its second argument.
For example, generateSubstrings("ABC", result); adds to result the strings: "", "A", "B", "C", "AB", "AC", "BC", "ABC" The order of the strings does not matter. You may use iteration for this problem
Use Java
The Java Code as per the above question is written below.
import java.util.*;
public class Main {
public static void generateSubstrings(String str, String t, ArrayList < String > result) {
result.add(t);
if (str.length() > 0) {
for (int i = 0; i < str.length(); i++) {
generateSubstrings(str.substring(i + 1, str.length()), t + str.charAt(i), result);
}
}
}
public static void main(String[] args) {
String str = "ABC";
String t = "";
ArrayList < String > result = new ArrayList < String > ();
generateSubstrings(str, t, result);
System.out.println(result);
}
}
Output Screenshot.
Beautified Code Screenshot.