-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathM0021.cpp
More file actions
41 lines (34 loc) · 795 Bytes
/
M0021.cpp
File metadata and controls
41 lines (34 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
Problem Statement: https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
*/
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
int sherlockAndAnagrams(string &s) {
int sum = 0;
string sub_s;
unordered_map<string, int> freq;
// Get all possible substrings
for (int i = 0; i < s.length(); i++)
for (int j = i + 1; j <= s.length(); j++) {
// Count anagrammatic substring
sub_s = string(s.begin() + i, s.begin() + j);
sort(sub_s.begin(), sub_s.end());
freq[sub_s]++;
}
// Sum all combinations of pairs
for (auto f: freq)
sum += (f.second * (f.second - 1)) / 2;
return sum;
}
int main() {
int q;
cin >> q;
while (q--) {
string s;
cin >> s;
cout << sherlockAndAnagrams(s) << endl;
}
}