generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem9.cs
More file actions
59 lines (49 loc) · 1.42 KB
/
Problem9.cs
File metadata and controls
59 lines (49 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
namespace LeetCode;
using System.Text;
/// <summary>
/// <see href="https://leetcode.com/problems/group-anagrams/">Group Anagrams</see>.
/// </summary>
public static class Problem9
{
/// <summary>
/// Given an array of strings strs, group the anagrams together. You can return the answer in any order.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="strs">Array to traverse.</param>
/// <returns>Grouped anagrams.</returns>
public static IList<IList<string>> GroupAnagrams(string[] strs)
{
var dict = new Dictionary<string, IList<string>>(strs.Length);
foreach (var str in strs)
{
var key = GenerateKey(str);
if (dict.ContainsKey(key))
{
dict[key].Add(str);
}
else
{
dict.Add(key, new List<string> { str });
}
}
return dict.Values.ToList();
}
private static string GenerateKey(string str)
{
var alphabet = new int[26];
foreach (var character in str)
{
alphabet[character - 'a']++;
}
var sb = new StringBuilder();
for (var i = 0; i < alphabet.Length; i++)
{
if (alphabet[i] != 0)
{
sb = sb.Append(alphabet[i]).Append((char)(i + 'a'));
}
}
return sb.ToString();
}
}