Sherlock and Anagrams

  • + 1 comment

    WOW!! I really liked your solution. I made a shorter version based on your code:

    public static int sherlockAndAnagrams(string s)
    {
       int counter = 0;
    
       for (int x = 1; x <= s.Length - 1; x++)
       {
          Dictionary<string, int> lista = new Dictionary<string, int>();
    
          for (int y = 0; y <= s.Length - x; y++)
          {
             var cadena = new string(s.Substring(y, x).OrderBy(c => c).ToArray());
             if (!lista.ContainsKey(cadena))
                lista.Add(cadena, 1);
             else
                lista[cadena] += 1;
          }
    
          lista.Values.Where(w => w > 1).ToList().ForEach(v =>
          {
             counter += v * (v - 1) / 2;
          });
       }
    
       return counter;
    }