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.

Leetcode 6th day challenge

C# Program

Solution – Easy to Understand

public class Solution {
    public IList<IList<string>> GroupAnagrams(string[] strs) {
        
        var map = new Dictionary<string,List<string>>();
        
        foreach(string s in strs)
        {
            int[] hash = new int[26];
            
            for(int i=0;i<s.Length;i++)
                hash[s[i]-'a']++;
            
            StringBuilder sb = new StringBuilder(s.Length);
            
            for(int i=0;i<26;i++)
            {
                if(hash[i] > 0)
                {
                    sb.Append((char)(i +'a'), hash[i]);
                }
            }
            
            string key = sb.ToString();
            
            if(!map.ContainsKey(key))
            {
                map.Add(key,new List<string>());
            }
                map[key].Add(s);
        }
        return map.Values.ToArray();
    }
}