Skip to content

Commit ccaca4c

Browse files
committed
Add 0049-group-anagrams.c
1 parent b797d10 commit ccaca4c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Diff for: c/0049-group-anagrams.c

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Represent an elemet of the hash map.
2+
typedef struct {
3+
char *key;
4+
char *strs[100];
5+
size_t size;
6+
UT_hash_handle hh;
7+
} StrsHash;
8+
9+
char *StrToKey(char *str) {
10+
int size = strlen(str);
11+
char c[26] = {0};
12+
char *key = malloc(size + 1);
13+
char *k = key;
14+
size_t i, j;
15+
16+
for (i = 0; i < size; i++) {
17+
c[str[i] - 'a']++;
18+
}
19+
20+
for (i = 0; i < 26; i++) {
21+
for (j = 0; j < c[i]; j++) {
22+
*k++ = 'a' + i;
23+
}
24+
}
25+
*k = '\0';
26+
return key;
27+
}
28+
29+
/**
30+
* Return an array of arrays of size *returnSize.
31+
* The sizes of the arrays are returned as *returnColumnSizes array.
32+
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
33+
*/
34+
char *** groupAnagrams(char ** strs, int strsSize, int* returnSize, int** returnColumnSizes){
35+
StrsHash *map = NULL;
36+
StrsHash *entry;
37+
char *key = NULL;
38+
char **resStrs = NULL;
39+
char ***result = NULL;
40+
int *colsSize = NULL;
41+
size_t i;
42+
43+
// Create a hash map.
44+
for (i = 0; i < strsSize; i++) {
45+
entry = NULL;
46+
key = StrToKey(strs[i]);
47+
HASH_FIND_STR(map, key, entry);
48+
if (!entry) {
49+
entry = malloc(sizeof(StrsHash));
50+
entry->key = key;
51+
entry->size = 0;
52+
HASH_ADD_KEYPTR(hh, map, key, strlen(key), entry);
53+
} else {
54+
free(key);
55+
}
56+
entry->strs[entry->size++] = strs[i];
57+
}
58+
59+
// Prepare the answer from the hash map.
60+
*returnSize = HASH_COUNT(map);
61+
colsSize = (int*)malloc(*returnSize * sizeof(int));
62+
result = (char***)malloc(*returnSize * sizeof(char**));
63+
*returnColumnSizes = colsSize;
64+
65+
for (entry = map, i = 0; entry != NULL; entry = entry->hh.next, i++) {
66+
colsSize[i] = entry->size;
67+
result[i] = entry->strs;
68+
}
69+
70+
return result;
71+
}

0 commit comments

Comments
 (0)