Permutations of a String

Here's one I choked hard on during the interview. Wrote it up pretty quick once I got home. It basically makes every possible combination of characters in a given string. Have I mentioned I suck in interviews?

Back to Code Samples

static public IEnumerable<string> GetPermutations(string word)
{
if (!String.IsNullOrEmpty(word) && word.Length > 1)
{

char character = word[0];

foreach (string subPermute in GetPermutations(word.Substring(1)))
{
for (int index = 0; index <= subPermute.Length; index++)
{
string pre = subPermute.Substring(0, index);
string post = subPermute.Substring(index);

if (post.Contains(character))
{
continue;
}

yield return pre + character + post;
}

}
}
else
{
yield return word;
}
}

Back to Code Samples