forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup-anagrams.cpp
More file actions
37 lines (33 loc) · 860 Bytes
/
group-anagrams.cpp
File metadata and controls
37 lines (33 loc) · 860 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
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<string>> groupAnagrams(vector<string> words) {
// Write your code here.
unordered_map<string, vector<int>> wordsMap;
vector<string> sortedWords;
for (auto& w : words) {
string sw = w;
sort(sw.begin(), sw.end());
sortedWords.push_back(sw);
}
for (int i = 0; i < words.size(); i++) {
string w = sortedWords[i];
auto it = wordsMap.find(w);
if (it != wordsMap.end()) {
(it->second).push_back(i);
} else {
wordsMap[w] = {i};
}
}
vector<vector<string>> result;
for (auto it = wordsMap.begin(); it != wordsMap.end(); it++) {
vector<int> indices = it->second;
vector<string> row;
for (auto& idx : indices) {
row.push_back(words[idx]);
}
result.push_back(row);
}
return result;
}