[Hacker Rank] Sherlock and Anagrams

Sherlock and Anagrams

  • Time : O(n^2)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int helper(string& s, int len) {
int res = 0, n = s.length();
unordered_map<string, int> freq;
for(int i = 0; i <= n - len; i++) {
string sub = s.substr(i, len);
sort(begin(sub), end(sub));
res += freq[sub];
freq[sub]++;
}
return res;
}

int sherlockAndAnagrams(string s) {
int res = 0, n = s.length();
for(int i = 1; i < n; i++) {
res += helper(s, i);
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/HackerRank/sherlock-and-anagrams/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.