Sherlock and Anagrams

  • + 0 comments

    C++20 :

    int sherlockAndAnagrams(string s) {
        int n = s.size();
        int anagram_count;
        
        for (int i = 1; i < n; i++){// i for size of substrings
        
        unordered_map<string, int> store;
        string substring;
        
            for (int j = 0; j < n-i+1; j++){// j for the starting position of the substring
            
                substring = s.substr(j,i); // substring starting at position j of length i
                
                sort(substring.begin(), substring.end()); // sort the substring
                
                store[substring]++; //count the number of times substring appears, up to rearrangement
            }
            for (auto t : store){
                if (t.second > 1){
                    anagram_count += (t.second)*(t.second-1)/2; // number of pairs is n choose 2 if n appears more than twice
                }
            }
        }
        return anagram_count;
    }