Leetcode49.Group Anagrams
在线提交: https://leetcode.com/problems/group-anagrams/
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
Related Topics: Hash Table String
Similar Questions: Valid Anagram Group Shifted Strings
思路:
方法1 已AC代码:
public class Solution
{
public IList<IList<string>> GroupAnagrams(string[] strs)
{
IList<IList<string>> res = new List<IList<string>>();
if (strs == null || strs.Length == 0)
return res;
Dictionary<string, int> dict = new Dictionary<string,int>();
foreach (var str in strs)
{
char[] ch = str.ToCharArray();
Array.Sort(ch);
string s = new string(ch);
if (dict.ContainsKey(s))
{
IList<string> list = res[dict[s]];
list.Add(str);
}
else
{
IList<string> list = new List<string>();
list.Add(str);
dict.Add(s, res.Count);
res.Add(list);
}
}
return res;
}
}
Rank:
You are here! Your runtime beats 30.94% of csharp submissions.