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\$
1
  • \$\begingroup\$What would be the intended output if the input string has duplicate characters (e.g. "ABBCA")?\$\endgroup\$
    – Martin R
    CommentedJul 9, 2018 at 12:21

1 Answer 1

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\$
5
  • \$\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
    CommentedJul 9, 2018 at 10:12
  • 1
    \$\begingroup\$sure @Graipher , make sense.Let me enhance.\$\endgroup\$
    – Vivek
    CommentedJul 9, 2018 at 10:15
  • \$\begingroup\$This solution does not produce same results as the code in the question. Missing "AC"\$\endgroup\$CommentedJul 9, 2018 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
    CommentedJul 9, 2018 at 11:36
  • 1
    \$\begingroup\$I have written the code only for the string having unique characters. Your code combines both unique and repeated characters. Thanks.\$\endgroup\$
    – Curious
    CommentedJul 13, 2018 at 9:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.