-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cs
55 lines (49 loc) · 1.31 KB
/
Solution.cs
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
using System.Collections.Generic;
public class Comparer : IEqualityComparer<string>
{
public bool Equals(string left, string right)
{
if (left.Length != right.Length) return false;
var leftCount = new int[26];
foreach (var ch in left)
{
++leftCount[ch - 'a'];
}
var rightCount = new int[26];
foreach (var ch in right)
{
var index = ch - 'a';
if (++rightCount[index] > leftCount[index]) return false;
}
return true;
}
public int GetHashCode(string obj)
{
var hashCode = 0;
for (int i = 0; i < obj.Length; ++i)
{
hashCode ^= 1 << (obj[i] - 'a');
}
return hashCode;
}
}
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
var dict = new Dictionary<string, List<string>>(new Comparer());
foreach (var str in strs)
{
List<string> list;
if (!dict.TryGetValue(str, out list))
{
list = new List<string>();
dict.Add(str, list);
}
list.Add(str);
}
foreach (var list in dict.Values)
{
list.Sort();
}
return new List<IList<string>>(dict.Values);
}
}