Thursday, February 18, 2010

How to find anagrams from a given list of strings using c#?

public static Dictionary> GetAnagramEquivalents()
{

// "cat", "tac", "army", "pam", "act", "map", "mary", "self"
// "act": "act", "cat", "tac"
// "army": "army", "mary"
// "map": "map", "pam"
// "self": "self"


List InputListStrings;

string[] inputStrings = new string[] {"cat", "tac", "army", "pam", "act", "map", "mary", "self","act", "act", "cat", "tac","army", "army", "mary","map","map", "pam","self","self"};
InputListStrings = inputStrings.ToList();
Dictionary> dictionaryReturnList = new Dictionary>();
for (int x = 0; x < InputListStrings.Count; ++x) { char[] InputCharArray = InputListStrings[x].ToCharArray(); Array.Sort(InputCharArray); string InputString = new string(InputCharArray); //check if the dic contains the key then add value to its corresponding list if (dictionaryReturnList.ContainsKey(InputString)) { dictionaryReturnList[InputString].Add(InputListStrings[x]); } else { dictionaryReturnList.Add(InputString, new List());
dictionaryReturnList[InputString].Add(InputListStrings[x]);
}
}
return dictionaryReturnList;
}

No comments:

Post a Comment