Skip to content

Commit 59ae5a2

Browse files
committed
Group Anagrams: hash, sort string.
1 parent 2e4442e commit 59ae5a2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Medium/049_Group-Anagrams.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include "../Header.h"
2+
3+
using namespace std;
4+
vector<vector<string>> groupAnagrams(vector<string>& strs) {
5+
vector<vector<string> > res;
6+
sort(strs.begin(), strs.end());
7+
8+
int cnt = 0;
9+
// hash_code index
10+
unordered_map<string, int> hash;
11+
for (int i = 0; i < strs.size(); i++) {
12+
int *tmp = new int[26];
13+
memset(tmp, 0, 26*4);
14+
for (int j = 0; j < strs[i].length(); j++) tmp[strs[i][j] - 'a']++;
15+
16+
string item = "";
17+
for (int i = 0; i < 26; i++) {
18+
item += (char)(tmp[i] & 0xff);
19+
item += (char)((tmp[i] >> 8) & 0xff);
20+
item += (char)((tmp[i] >> 16) & 0xff);
21+
item += (char)((tmp[i] >> 24) & 0xff);
22+
}
23+
24+
if (hash.find(item) == hash.end()) {
25+
hash[item] = cnt++;
26+
vector<string> item{strs[i]};
27+
res.push_back(item);
28+
} else res[ hash[item] ].push_back(strs[i]);
29+
}
30+
return res;
31+
}
32+

0 commit comments

Comments
 (0)