-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0049-group-anagrams.c
71 lines (63 loc) · 1.8 KB
/
0049-group-anagrams.c
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Represent an elemet of the hash map.
typedef struct {
char *key;
char *strs[100];
size_t size;
UT_hash_handle hh;
} StrsHash;
char *StrToKey(char *str) {
int size = strlen(str);
char c[26] = {0};
char *key = malloc(size + 1);
char *k = key;
size_t i, j;
for (i = 0; i < size; i++) {
c[str[i] - 'a']++;
}
for (i = 0; i < 26; i++) {
for (j = 0; j < c[i]; j++) {
*k++ = 'a' + i;
}
}
*k = '\0';
return key;
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
char *** groupAnagrams(char ** strs, int strsSize, int* returnSize, int** returnColumnSizes){
StrsHash *map = NULL;
StrsHash *entry;
char *key = NULL;
char **resStrs = NULL;
char ***result = NULL;
int *colsSize = NULL;
size_t i;
// Create a hash map.
for (i = 0; i < strsSize; i++) {
entry = NULL;
key = StrToKey(strs[i]);
HASH_FIND_STR(map, key, entry);
if (!entry) {
entry = malloc(sizeof(StrsHash));
entry->key = key;
entry->size = 0;
HASH_ADD_KEYPTR(hh, map, key, strlen(key), entry);
} else {
free(key);
}
entry->strs[entry->size++] = strs[i];
}
// Prepare the answer from the hash map.
*returnSize = HASH_COUNT(map);
colsSize = (int*)malloc(*returnSize * sizeof(int));
result = (char***)malloc(*returnSize * sizeof(char**));
*returnColumnSizes = colsSize;
for (entry = map, i = 0; entry != NULL; entry = entry->hh.next, i++) {
colsSize[i] = entry->size;
result[i] = entry->strs;
}
return result;
}