-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintAnagramsTogether.cpp
102 lines (89 loc) · 2.26 KB
/
PrintAnagramsTogether.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution {
public:
struct Node {
Node *arr[26];
bool flag = false;
bool contains(char ch) {
return arr[ch - 'a'] != nullptr;
}
void put(char ch, Node *newNode) {
arr[ch - 'a'] = newNode;
}
Node *getNext(char ch) {
return arr[ch - 'a'];
}
void setFlag() {
flag = true;
}
bool isFlagSet() {
return flag;
}
};
void insert(Node *root, string word) {
for (int i = 0; i < word.size(); i++) {
if (!root->contains(word[i])) {
root->put(word[i], new Node());
}
root = root->getNext(word[i]);
}
root->setFlag();
}
bool search(Node *root, string word) {
for (int i = 0; i < word.size(); i++) {
if (!root->contains(word[i])) {
return false;
}
root = root->getNext(word[i]);
}
return root != nullptr && root->isFlagSet();
}
vector<vector<string>> Anagrams(vector<string> &string_list) {
map<string, vector<string>> mp;
vector<vector<string>> ans;
string temp;
Node *root = new Node();
for (auto s : string_list) {
temp = s;
sort(temp.begin(), temp.end());
mp[temp].push_back(s);
}
for (auto ele : mp) {
ans.push_back(ele.second);
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<string> string_list(n);
for (int i = 0; i < n; ++i)
cin >> string_list[i];
Solution ob;
vector<vector<string> > result = ob.Anagrams(string_list);
sort(result.begin(), result.end());
for (int i = 0; i < result.size(); i++)
{
for (int j = 0; j < result[i].size(); j++)
{
cout << result[i][j] << " ";
}
cout << "\n";
}
}
return 0;
}
// } Driver Code Ends