forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0049-group-anagrams.cpp
39 lines (34 loc) · 1.14 KB
/
0049-group-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
/*
Given array of strings, group anagrams together (same letters diff order)
Ex. strs = ["eat","tea","tan","ate","nat","bat"] -> [["bat"],["nat","tan"],["ate","eat","tea"]]
Count chars, for each string use total char counts (naturally sorted) as key
Time: O(n x l) -> n = length of strs, l = max length of a string in strs
Space: O(n x l)
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (int i = 0; i < strs.size(); i++) {
string key = getKey(strs[i]);
m[key].push_back(strs[i]);
}
vector<vector<string>> result;
for (auto it = m.begin(); it != m.end(); it++) {
result.push_back(it->second);
}
return result;
}
private:
string getKey(string str) {
vector<int> count(26);
for (int j = 0; j < str.size(); j++) {
count[str[j] - 'a']++;
}
string key = "";
for (int i = 0; i < count.size(); i++) {
key.append(to_string(count[i]) + '#');
}
return key;
}
};