|
| 1 | +/* |
| 2 | +Given an array of strings strs, group the anagrams together. You can return the answer in any order. |
| 3 | +
|
| 4 | +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, |
| 5 | +typically using all the original letters exactly once. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: strs = ["eat","tea","tan","ate","nat","bat"] |
| 10 | +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] |
| 11 | +Example 2: |
| 12 | +
|
| 13 | +Input: strs = [""] |
| 14 | +Output: [[""]] |
| 15 | +Example 3: |
| 16 | +
|
| 17 | +Input: strs = ["a"] |
| 18 | +Output: [["a"]] |
| 19 | + * */ |
| 20 | +#define KEYLEN 128 |
| 21 | + |
| 22 | +typedef struct { |
| 23 | + char key[KEYLEN]; |
| 24 | + int listSize; |
| 25 | + char **list; |
| 26 | + UT_hash_handle hh; |
| 27 | +} Map; |
| 28 | + |
| 29 | +int cmpFunc(const void *a, const void *b) { return *(char *) a - *(char *) b; } |
| 30 | + |
| 31 | +char ***groupAnagrams(char **strs, int strsSize, int **columnSizes, int *returnSize) { |
| 32 | + Map *map = NULL, *elem = NULL, *tmp; |
| 33 | + char strBuf[KEYLEN], ***result; |
| 34 | + int mapIndx = 0; |
| 35 | + if (strsSize <= 0) return NULL; |
| 36 | + for (int i = 0; i < strsSize; i++) { |
| 37 | + strncpy(strBuf, strs[i], KEYLEN); |
| 38 | + qsort(strBuf, strlen(strs[i]), sizeof(char), cmpFunc); |
| 39 | + HASH_FIND_STR(map, strBuf, elem); |
| 40 | + if (!elem) { |
| 41 | + elem = malloc(sizeof(Map)); |
| 42 | + strncpy(elem->key, strBuf, KEYLEN); |
| 43 | + elem->listSize = 1; |
| 44 | + elem->list = malloc(sizeof(char **)); |
| 45 | + elem->list[0] = strs[i]; |
| 46 | + HASH_ADD_STR(map, key, elem); |
| 47 | + } else { |
| 48 | + elem->listSize++; |
| 49 | + elem->list = realloc(elem->list, elem->listSize * sizeof(char **)); |
| 50 | + elem->list[elem->listSize - 1] = strs[i]; |
| 51 | + } |
| 52 | + } |
| 53 | + *returnSize = HASH_COUNT(map); |
| 54 | + result = malloc(*returnSize * sizeof(char **)); |
| 55 | + *columnSizes = malloc(*returnSize * sizeof(int)); |
| 56 | + HASH_ITER(hh, map, elem, tmp) |
| 57 | + { |
| 58 | + (*columnSizes)[mapIndx] = elem->listSize; |
| 59 | + result[mapIndx++] = elem->list; |
| 60 | + } |
| 61 | + return result; |
| 62 | +} |
0 commit comments