-
Notifications
You must be signed in to change notification settings - Fork 8
/
all-anagrams.cpp
executable file
·69 lines (64 loc) · 2.02 KB
/
all-anagrams.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
68
69
/*
Given an array of strings, find all anagram pairs in the given array.
Input: arr[] = {"geeksquiz", "geeksforgeeks", "abcd",
"forgeeksgeeks", "zuiqkeegs"};
Output: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs)
*/
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
// utility function for printing
// anagram list
void printAnagram(unordered_map<string,vector<string> > &store){
unordered_map<string,vector<string> > :: iterator it;
for(it = store.begin(); it != store.end(); it++){
vector<string> temp_vec(it->second);
int size = temp_vec.size();
if(size > 1){
for(int i=0 ;i<size; i++){
cout << temp_vec[i]<<" ";
}
cout << "\n";
}
}
}
// utility function for storing the vector of strings
// into HashMap
void storeInMap(vector<string> &vec){
unordered_map<string,vector<string> > store;
for(int i=0; i<vec.size(); i++){
string tempString(vec[i]);
sort(tempString.begin(),tempString.end());
//check for sorted string if it already exists
if(store.find(tempString) == store.end()){
vector <string> temp_vec;
temp_vec.push_back(vec[i]);
store.insert(make_pair(tempString,temp_vec));
}else{
//push new string to already existing key
vector<string> temp_vec(store[tempString]);
temp_vec.push_back(vec[i]);
store[tempString] = temp_vec;
}
}
// print utility function for printing
// all the anagrams
printAnagram(store);
}
int main(){
// initialize vector of strings
vector <string> arr;
arr.push_back("geeksquiz");
arr.push_back("geeksforgeeks");
arr.push_back("abcd");
arr.push_back("forgeeksgeeks");
arr.push_back("zuiqkeegs");
arr.push_back("cat");
arr.push_back("act");
arr.push_back("tca");
// utility function for storing strings into hashmap
storeInMap(arr);
return 0;
}