Sherlock and Anagrams

  • + 0 comments

    C#

        public static int sherlockAndAnagrams(string s)
        {
            int pairsCount = 0;
            Dictionary<string, List<string>> subs = 
                new Dictionary<string, List<string>>();
            
            for (int l = 1; l <= s.Length; l++) {
                for (int i = 0; i <= s.Length - l; i++) {
                    string subStr = s.Substring(i, l);
                    string hc = GetHashCode(subStr);
                    if (!subs.ContainsKey(hc))
                        subs.Add(hc, new List<string>());
                    subs[hc].Add(subStr);                
                }
            }
            
            foreach (var kv in subs) {
                if (kv.Value.Count() > 1)
                    pairsCount += (kv.Value.Count() * (kv.Value.Count()-1))/2;
            }
            
            return pairsCount;
        }
        
        private static string GetHashCode(string subStr) {
            int[] chars = new int[26];
            foreach (char ch in subStr) {
                chars[(int)(ch - 'a')]++;
            }
            var strCodes = chars.Select(c => c.ToString());
            return string.Join("", strCodes);
        }