|
| 1 | +using System.Text; |
| 2 | + |
| 3 | +namespace LeetCodeSolutions.HashMap |
| 4 | +{ |
| 5 | + class GroupAnagramsSolution |
| 6 | + { |
| 7 | + public IList<IList<string>> GroupAnagrams(string[] strs) |
| 8 | + { |
| 9 | + // Dictionary to hold groups of anagrams |
| 10 | + Dictionary<string, List<string>> anagramGroups = new Dictionary<string, List<string>>(); |
| 11 | + |
| 12 | + foreach (string str in strs) |
| 13 | + { |
| 14 | + string key = GenerateAnagramKey(str); |
| 15 | + |
| 16 | + // Create new group or add to existing |
| 17 | + if (!anagramGroups.TryGetValue(key, out List<string> group)) |
| 18 | + { |
| 19 | + group = new List<string>(); |
| 20 | + anagramGroups[key] = group; |
| 21 | + } |
| 22 | + group.Add(str); |
| 23 | + } |
| 24 | + |
| 25 | + return new List<IList<string>>(anagramGroups.Values); |
| 26 | + } |
| 27 | + |
| 28 | + private string GenerateAnagramKey(string s) |
| 29 | + { |
| 30 | + int[] charCounts = new int[26]; |
| 31 | + // Count character frequencies |
| 32 | + foreach (char c in s) |
| 33 | + { |
| 34 | + charCounts[c - 'a']++; |
| 35 | + } |
| 36 | + |
| 37 | + // Build unique key from counts |
| 38 | + StringBuilder keyBuilder = new StringBuilder(); |
| 39 | + foreach (int count in charCounts) |
| 40 | + { |
| 41 | + keyBuilder.Append(count).Append('#'); |
| 42 | + } |
| 43 | + |
| 44 | + return keyBuilder.ToString(); |
| 45 | + } |
| 46 | + |
| 47 | + [Test(Description = "https://leetcode.com/problems/group-anagrams/")] |
| 48 | + [Category("Medium")] |
| 49 | + [Category("LeetCode")] |
| 50 | + [Category("Group Anagrams")] |
| 51 | + [TestCaseSource(nameof(Input))] |
| 52 | + [Category("HashMap")] |
| 53 | + [Category("TopInterview")] |
| 54 | + public void Test1((IList<IList<string>> Output, string[] Input) item) |
| 55 | + { |
| 56 | + var response = GroupAnagrams(item.Input); |
| 57 | + // Normalize both actual and expected results |
| 58 | + var normalizedResponse = NormalizeAnagramGroups(response); |
| 59 | + var normalizedExpected = NormalizeAnagramGroups(item.Output); |
| 60 | + |
| 61 | + Assert.That(normalizedResponse, Is.EqualTo(normalizedExpected)); |
| 62 | + } |
| 63 | + |
| 64 | + private IList<List<string>> NormalizeAnagramGroups(IList<IList<string>> groups) |
| 65 | + { |
| 66 | + return groups |
| 67 | + .Select(group => |
| 68 | + group.OrderBy(s => s).ToList() // Sort individual anagrams |
| 69 | + ) |
| 70 | + .OrderBy(group => |
| 71 | + group.FirstOrDefault() // Sort groups by first element |
| 72 | + ) |
| 73 | + .ToList(); |
| 74 | + } |
| 75 | + |
| 76 | + public static IEnumerable<(IList<IList<string>> Output, string[] Input)> Input => |
| 77 | + new List<(IList<IList<string>> Output, string[] Input)>() |
| 78 | + { |
| 79 | + ( [["bat"],["nat","tan"],["ate","eat","tea"]], ["eat","tea","tan","ate","nat","bat"]), |
| 80 | + }; |
| 81 | + } |
| 82 | +} |
0 commit comments