-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagrams.cpp
34 lines (28 loc) · 842 Bytes
/
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
class Solution {
public:
/**
* @param strs: A list of strings
* @return: A list of strings
*/
vector<string> anagrams(vector<string> &strs) {
map<string, vector<string> > collection;
vector<string> result;
for (auto &str : strs) {
string copy(str);
sort(copy.begin(), copy.end());
auto it = collection.find(copy);
if (it == collection.end()) {
vector<string> l = { str };
collection[copy] = l;
} else {
(*it).second.push_back(str);
}
}
for (auto &pair : collection) {
if (pair.second.size() > 1) {
result.insert(result.begin(), pair.second.begin(), pair.second.end());
}
}
return result;
}
};