LeetCode 49. 字母異位詞分組 Group Anagrams(C語言)
阿新 • • 發佈:2018-12-27
題目描述:
給定一個字串陣列,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字串。
示例:
輸入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
輸出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
說明:
- 所有輸入均為小寫字母。
- 不考慮答案輸出的順序。
題目解答:
方法1:Hash
將字母相同的單詞的hash值存下來。遍歷陣列單詞,如果其hash值是已有map的中的某一個,則直接將單詞加入到對應的行,不存在則加入map。因為我才用的hash關係是將單詞中不同字母出現的次數記錄下來,其作為hash值,hash關係比較簡單,所以其效率沒有那麼高,較慢。
執行時間200ms左右,程式碼如下。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
#define SIZE 27
void countWord(char* word, int* map) {
int len = 0;
while (*word) {
len++;
map[*word - 'a']++;
word++;
}
map[SIZE - 1] = len;
}
char*** groupAnagrams(char** strs, int strsSize, int** columnSizes, int* returnSize) {
if(strsSize == 0)
return NULL;
char*** result = NULL;
int i = 0, j = 0, n = strsSize;
int size = 0;
int** map = (int**)malloc(n * sizeof(int*));
for(i = 0; i < n; i++)
map[i] = (int*)calloc(SIZE, sizeof(int));
for(i = 0; i < n; i++) {
int temp[SIZE] = { 0 };
countWord(strs[i], temp);
int len = temp[SIZE - 1];
for(j = 0; j < size; j++) {
if(len != map[j][SIZE - 1])
continue;
if(0 == memcmp(temp, map[j], SIZE * sizeof(int))) {
columnSizes[0][j]++;
result[j] = (char**)realloc(result[j], columnSizes[0][j] * sizeof(char*));
result[j][columnSizes[0][j] - 1] = (char*)malloc((len + 1) * sizeof(char));
memcpy(result[j][columnSizes[0][j] - 1], strs[i], (len + 1) * sizeof(char));
break;
}
}
if(j == size) {
size++;
columnSizes[0] = (int*)realloc(columnSizes[0], size * sizeof(int));
columnSizes[0][size - 1] = 1;
result = (char***)realloc(result, size * sizeof(char**));
result[size - 1] = (char**)malloc(1 * sizeof(char*));
result[size - 1][0] = (char*)malloc((len + 1) * sizeof(char));
memcpy(result[size - 1][0], strs[i], (len + 1) * sizeof(char));
memcpy(map[size - 1], temp, SIZE * sizeof(int));
}
}
for(i = 0; i < n; i++)
free(map[i]);
free(map);
*returnSize = size;
return result;
}
可以更改Hash值的計算方法,來提高效率。