forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanagrams_substrings.cpp
67 lines (45 loc) · 963 Bytes
/
anagrams_substrings.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<map>
#include<vector>
using namespace std;
/*
1. Generate all substrings
2. Generate their hash
3. Hash the 'hash' values to club all anagrams in single bucket, to get their frequency count
4. From freq count, we can easily count the paris
*/
vector<int> getHashValue(string s,int i,int j){
vector<int> freq(26,0);
//iterate over the original string from i to j to fill this vector
for(int k=i;k<=j;k++){
char ch = s[k];
freq[ch-'a']++;
}
return freq;
}
int anagrams_substrings(string s){
map<vector<int> , int > m;
for(int i=0;i<s.length();i++){
for(int j=i; j<s.length();j++){
//Substring S[i...j]
vector<int> h = getHashValue(s,i,j);
//put it inside a map
m[h]++;
}
}
//pairs
int ans = 0;
for(auto p : m){
int freq = p.second;
if(freq>=2){
ans += (freq)*(freq-1)/2;
}
}
return ans;
}
int main(){
string s;
cin>>s ;
cout<<anagrams_substrings(s)<<endl;
return 0;
}