Sherlock and Anagrams

  • + 0 comments

    C#

    public static int sherlockAndAnagrams(string s)
    {
        var anagrams = 0;
        var frequency = new Dictionary<string, int>();
    
        for (int i = 0; i < s.Length; i++)
        {
            for (int j = i + 1; j <= s.Length; j++)
            {
                var sub = new string(s.Substring(i, j - i).OrderBy(s => s).ToArray());
    
                if (frequency.ContainsKey(sub))
                    frequency[sub]++;
                else
                    frequency[sub] = 1;
            }
        }
    
        foreach (var (key, value) in frequency)
            anagrams += value * (value - 1) / 2;
    
        return anagrams;
    }