1
\$\begingroup\$

I wrote this code for printing all sets of a String. It also prints the empty subset. Is this the right approach

public class AllSubSet {

    public static void allSet(String s, String t) {
        System.out.print(t + " ");
        if (s.length() > 0) {
            for (int i = 0; i < s.length(); i++) {
                allSet(s.substring(i + 1, s.length()), t + s.charAt(i));
            }
        }
    }

    public static void main(String args[]) {
        String a = "ABC";
        String t = "";
        allSet(a, t);
    }
}
\$\endgroup\$
  • \$\begingroup\$ What would be the intended output if the input string has duplicate characters (e.g. "ABBCA")? \$\endgroup\$ – Martin R Jul 9 '18 at 12:21
1
\$\begingroup\$

If I have understood correctly, you're aiming for all subset of a String. Through your code for String = "ABC"; //Result is -- > A AB ABC AC B BC C

However, for

String = "ABB";
// Result is --> A AB ABB AB B BB B (You see AB twice as well as letter B).

So to make it more clear for unique subsets, added a set implementation.

TreeSet (extra sorted feature over hash), as below : (using same recursion)

public class Test {

 public static void allSet(String s, String t, Set<String> set) {
     // System.out.print(t + " ");   will print later.
      if(!"".equalsIgnoreCase(t))
      set.add(t);
      if (s.length() > 0) {
          for (int i = 0; i < s.length(); i++) {
              allSet(s.substring(i + 1, s.length()), t + s.charAt(i),set);
          }
      }
  }
public static void main(String args[]) {
    String a = "ABB";
    String t = "";
    Set<String> set = new TreeSet<String>();
    allSet(a, t, set);
    System.out.println(set.toString());
   }



// Now, result --> [A, AB, ABB, B, BB]
\$\endgroup\$
  • \$\begingroup\$ We are not just looking for alternative implementations, but want to improve the future coding of the OP and everyone else. So you should describe why this is different and why it is better. At least include what is currently in your comment under the OP's question. \$\endgroup\$ – Graipher Jul 9 '18 at 10:12
  • 1
    \$\begingroup\$ sure @Graipher , make sense.Let me enhance. \$\endgroup\$ – VibrantVivek Jul 9 '18 at 10:15
  • \$\begingroup\$ This solution does not produce same results as the code in the question. Missing "AC" \$\endgroup\$ – Sharon Ben Asher Jul 9 '18 at 10:19
  • \$\begingroup\$ This prints all (contiguous) substrings of the given string, not all subsets that can be formed with characters of the given string. \$\endgroup\$ – Martin R Jul 9 '18 at 11:36
  • \$\begingroup\$ I have written the code only for the string having unique characters. Your code combines both unique and repeated characters. Thanks. \$\endgroup\$ – Curious Jul 13 '18 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.