LeetCode Online Judge 题目C# 练习 - Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
e.g. "tea","and","ate","eat","dan". return "and","dan","tea","ate","eat"
anangrams意思是重新排列字母顺序构成一个新词。
1 public static List<string> Anagrams(string[] S) 2 { 3 List<string> ret = new List<string>(); 4 List<string> sortedS = new List<string>(); 5 Dictionary<string, List<int>> map = new Dictionary<string, List<int>>(); 6 7 for (int i = 0; i <= S.GetUpperBound(0); i++) 8 { 9 char[] temp = S[i].ToCharArray(); 10 Array.Sort(temp); 11 sortedS.Add(new string(temp)); 12 } 13 for (int i = 0; i <= sortedS.Count - 1; i++) 14 { 15 if (map.ContainsKey(sortedS[i])) 16 map[sortedS[i]].Add(i); 17 else 18 map.Add(sortedS[i], new List<int> { i }); 19 } 20 21 foreach (var item in map) 22 { 23 if(item.Value.Count > 1) 24 foreach (int index in item.Value) 25 { 26 ret.Add(S[index]); 27 } 28 } 29 return ret; 30 }
代码分析:
这题解题关键是先把所有string先排列,然后放到一个新的List<string> SortedS里面。
之后就简单了,用一个Dictionary<string, List<int>>, 把在SortedS里面相同的string记录起来他的index。然后再迭代这个map,把Value.Count > 1的回到原来的S[]里面找。
用Dictionary插入元素的时候要注意一下:
- 在C++ STL提供的map里,插入的时候直接map[Key] = Value; 就可以了,但是C#里头如果map.ContainKey(Key) == false; 直接map[Key] = Value会抛出异常,我们要使用map.Add(Key, Value);