Thursday, December 15, 2016

Get subset of a String

Given a String, find all subset of the String.
Let's take a example for this.
String s = "abc", and subset we are looking for is
{"a","b","c","ab","ac","bc","abc"}
The number of subset is 2^n - 1, where n is the length of a string.
If we include empty subset, it will be just 2^n.

The first obvious way is to use recursion.
public void subsets(String s, ArrayList subset){
        if(word.length() == 1){
            subset.add(s);
            return;
        }
        else {
            String first = s.substring(0,1);
            String right = s.substring(1);
            subsets(right, subset);
            int size = subset.size();
            for (int i = 0; i < size; i++){
                String temp = first + subset.get(i);
                subset.add(temp);
            }
            subset.add(first);
            return;
        }
    }

Without recursion, we need to think about how the subset is formed.
When something is linked to 2^n, it means there are two possible choices in every n locations.
So, we have binary string with length n. When the bit at the position i is 1, we need to add the character at i to the subset element.
Let's look at the example above.
If the length of string is 3, we have binary string with length 3.

000 -> empty string
001 --> c
010 --> b
100 --> a
101 --> ac
110 --> ab
011 --> bc
111 --> abc

public void subsets(String s) {
       int len = s.length();
       for (int i=1; i< power(2,len);i++) {
            //int j = i << 1;
            for (int j=0;j<3 j="" p="">                if ((i & (1<                    System.out.print(s.charAt(j) + " ");
                }
            }
            System.out.println();
        }
}







No comments:

Post a Comment