Sherlock and Anagrams

  • + 0 comments
    static string sortString(string s) {
            const int MAX_CHAR = 26;
            int[] charCount = new int[MAX_CHAR];
            StringBuilder sb = new StringBuilder();
            
            foreach (char ch in s) {
                charCount[ch - 'a']++;
            }
            
            for (int i = 0; i < MAX_CHAR; i++) {
                for (int j = 0; j < charCount[i]; j++) {
                    sb.Append('a' + i);
                }
            }
            
            return sb.ToString();
        }
        
        static int calculateTotalCombinations(int n){    
            return (n * (n -1)) / 2;
        }
        
        static Dictionary<string, int> findSubstrings(string s) 
        {  
            Dictionary<string, int> dic = new Dictionary<string, int>();
        
            for(int i = 1; i <= s.Length; i++) 
            { 
                for(int j = 0; j <= s.Length - i; j++) 
                {   
                    var substring = sortString(s.Substring(j, i));
                    
                    // Using Substring() function 
                    if(dic.ContainsKey(substring)){
                      dic[substring] = dic[substring] + 1; 
                      continue; 
                    }
                    
                    dic.Add(substring, 1);
                } 
            } 
            
            return dic;
        } 
    
        public static int sherlockAndAnagrams(string s)
        {
            var dic = findSubstrings(s);
            int totalAnagrams = 0;
            
            foreach(var item in dic){
                totalAnagrams+= calculateTotalCombinations(item.Value); 
            }
            
            return totalAnagrams;
        }