Combinations of a String

Question: Write an algorithm to print all possible combinations of characters in a string.

Answer: Any thoughts? One thing is for sure, we can definitely use some recursive logic here. Let’s approach this problem methodically. Since we need to generate combinations, we can start with a single character and then continue to add a character to combinations we have seen so far. Let’s use “abc” as an example.

Here’s some code in Java (for a change :) ) to achieve what we’ve described above.

void combine(String instr, StringBuffer outstr, int index)
{
    for (int i = index; i < instr.length(); i++)
    {
        outstr.append(instr.charAt(i));
        System.out.println(outstr);
        combine(instr, outstr, i + 1);
        outstr.deleteCharAt(outstr.length() - 1);
    }
} 

combine("abc", new StringBuffer(), 0);

Have a better solution? Please let us know through the comments section.

Get a free subscription to Oracle magazine published by Oracle Corp.
 Powered by Max Banner Ads 

Related posts:

  1. Permutations of a String
  2. Anagrams in an Array of Strings
  3. First Non-Repeated Character
  4. Reverse the Order of Words in a String
  5. Reverse a String

2 Responses

  1. JM says:

    Above algorithm generates repeats. Ex, input string is aaa

  2. abbulu says:

    Other solution is multi the characters in each string with integer values and 256. Then sort the values and compare values next to each if any two numbers equals then corresponding strings are anagrams. O(n)+O(nlogn)+O(n)

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>