-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathanagrams.cpp
More file actions
30 lines (25 loc) · 727 Bytes
/
anagrams.cpp
File metadata and controls
30 lines (25 loc) · 727 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
// Time: O(n * klogk), k is max length of strings
// Space: O(m), m is number of anagram groups
class Solution {
public:
/**
* @param strs: A list of strings
* @return: A list of strings
*/
vector<string> anagrams(vector<string> &strs) {
unordered_map<string, int> table;
for (auto str : strs) {
sort(str.begin(), str.end());
++table[str];
}
vector<string> anagrams;
for (const auto& str : strs) {
string sorted_str(str);
sort(sorted_str.begin(), sorted_str.end());
if (table[sorted_str] >= 2) {
anagrams.emplace_back(str);
}
}
return anagrams;
}
};