Sherlock and Anagrams

  • + 0 comments

    C#

    public static int sherlockAndAnagrams(string s)
    {
        var anagrams = 0;
        var windows = s.Length - 1;
    
        for (int w = 1; w <= windows; w++)
        {
            for (int i = 0; i <= s.Length - w - 1; i++)
            {
                for (int j = i + 1; j <= s.Length - w; j++)
                {
                    var str1 = s.Substring(i, w);
                    var str2 = s.Substring(j, w);
    
                    var sortedStr1 = new string(str1.OrderBy(c => c).ToArray());
                    var sortedStr2 = new string(str2.OrderBy(c => c).ToArray());
    
                    if (sortedStr1 == sortedStr2)
                    {
                        anagrams++;
                    }
                }
            }
        }
    
        return anagrams;
    }