LeetCode: Group Anagrams C#
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase. The order of your output does not matter.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/778/
/// </summary>
[TestClass]
public class GroupAnagramsTest
{
[TestMethod]
public void TestMethod1()
{
string[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
var result = GroupAnagramsClass.GroupAnagrams(strs);
List<IList<string>> expected = new List<IList<string>>();
expected.Add( new List<string> {"eat", "tea", "ate"});
expected.Add( new List<string> {"tan", "nat"});
expected.Add( new List<string> {"bat"});
for (int i = 0; i < result.Count; i++)
{
CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
}
}
}
public class GroupAnagramsClass
{
public static IList<IList<string>> GroupAnagrams(string[] strs)
{
Dictionary<char[], List<string>> dict = new Dictionary<char[], List<string>>(new CharComparer());
foreach (var str in strs)
{
var key = str.ToCharArray();
Array.Sort(key);
if (!dict.TryGetValue(key, out var temp))
{
temp = dict[key] = new List<string>();
}
temp.Add(str);
}
List<IList<string>> res = new List<IList<string>>(dict.Values.ToList());
return res;
}
}
public class CharComparer : IEqualityComparer<char[]>
{
public bool Equals(char[] x, char[] y)
{
if (x == null || y == null)
{
return false;
}
if (x.Length != y.Length)
{
return false;
}
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public int GetHashCode(char[] obj)
{
return 0;
}
}
}
Please review for performance.
I don't like me copying the dictionary into IList<IList<string>
. Is there a better way to do so, considering this the desired API defined by the question?