-4

I need the code (or snippet of the code for the following problem or hint on how to solve):

A sub sequence of string s is obtained by deleting one or more characters from s. The set of sub sequences for string s = abc would be a, ab, ac, abc, b, bc, c, and the empty string (which is a sub sequence of all strings).

Find all possible sub sequences for s and print them in lexicographic order.

This is what i have come out with but it's not working:

TreeSet<String> ls = new TreeSet<>();

    for(int i=0;i<s.length();i++)
    {

        for(int j=i;j<s.length();j++)
        {
            StringBuffer sb = new StringBuffer();

            for(int k=i;k<j+1;k++)
            {
                sb.append(s.charAt(k));
            }

            ls.add(sb.toString());
        }

    }




    return ls.toArray(new String[ls.size()]);

Result:

TestCase : abc

Output: a ab abc b bc c

Expected Output: a ab abc ac b bc c

snapGeek
  • 41
  • 1
  • 2
  • 5

1 Answers1

0

Your code looks for substrings, which are consecutive sequences of characters from the original string. However, "ac" is taken from non-consecutive characters of the input string, and you're not going to get that output using your approach.

One thing to note is that your input string has 3 characters, there are 8 possible outputs (including the empty string), and 23 = 8. What this should suggest is that you want all 8 possible combinations of 3 booleans, where each boolean can be true or false. Each boolean would then correspond to one character of the input string, where true means that character from the input string is in the output, and false means that it isn't. You then generate your 8 output strings by looking at all possible true/false combinations. Your code to get them sorted by using a TreeSet appears to be working fine.

There are a few possible approaches:

(1) Use an array of boolean and find all the possible combinations. You could start with all false, then change the first one from false to true, but then change it back with the realization that whenever you change a boolean from true to false, you then have to change the next boolean in the array also. You could try doing this on paper to see how it would work.

(2) Recognize that your array of boolean is equivalent to bits of an integer, and you can get all the possible combinations of bits just by repeatedly adding 1 to the integer. You'd then use bit operations to figure out which characters of the input string to include.

(3) Recursion. If your input string is "abc", find all subsequences of "bc" recursively. For each subsequence S of "bc", S will be one subsequence of "abc", and "a" + S will be another.

ajb
  • 31,309
  • 3
  • 58
  • 84