C# - O(n) time, O(n) space - using Hash - simple


  • 0

    Group like strings by converting each string to a "key" which is just the string shifted so the first char is 'a'. The hash value is a List of strings with common key.

        public IList<IList<string>> GroupStrings(string[] strings) 
        {
            Dictionary<string, IList<string>> map = new Dictionary<string, IList<string>>();
            foreach (string s in strings)
            {
                string key = GetKey(s);
                if (!map.ContainsKey(key)) map[key] = new List<string>();
                map[key].Add(s);
            }
            return map.Values.ToList();
        }
        
        public string GetKey(string s)
        {
            char[] chars = new char[s.Length];
            for (int i = 0 ; i < s.Length; i++)
            {
                chars[i] = (char)((26 + s[i] - (s[0] - 'a')) % 26) ;
            }
            return new string(chars);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.