/**
* 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().
*/
typedef struct node{
int index;
int key;
int cnt[26];
} Node;
#define LEN 1000
typedef struct hash_node_t{
int index;
int ret_index;
int col_index;
Node *wnode;
struct hash_node_t *next;
} HaNode;
int hash_index(Node *node){
return node->key % LEN;
}
void hash_init(HaNode **hash_table, int len){
int i;
for(i=0; inext;
free(last);
}
}
return;
}
void hash_insert(HaNode **hash_table, HaNode *node){
int index = hash_index(node->wnode);
node->next = hash_table[index];
hash_table[index] = node;
}
HaNode *hash_find(HaNode **hash_table, Node *wnode, int key){
int index = hash_index(wnode);
HaNode *p = hash_table[index];
while(p){
if(p->wnode->key == key && !memcmp(wnode->cnt, p->wnode->cnt, 26*sizeof(int))){
break;
}
p = p->next;
}
return p;
}
/*
* 方法二:
* 时间复杂度O(N),每访问一个单词时,到hash表中查找,看是否有能匹配的单词,如果有的话,直接使用找到的hash节点信息,
* 将当前单词插入到返回结果中,并修改hash节点信息。
* 如果查找不到,则需要重新构建哈希节点,并插入哈希表。
*/
char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** columnSizes) {
int i, j;
Node *arr = (Node *)malloc(sizeof(Node) * strsSize);
bool *vist = (bool *)malloc(sizeof(bool) * strsSize);
char *** ret = (char ***)malloc(sizeof(char**) * strsSize);
int *col_size = (int *)malloc(sizeof(int) * strsSize);
int ret_index = 0;
int col_index = 0;
HaNode **hash_table = (HaNode **)malloc(sizeof(HaNode *) * LEN);
HaNode *p = NULL;
int key;
hash_init(hash_table, LEN);
memset(arr, 0, sizeof(Node) * strsSize);
for(i=0; iret_index][p->col_index++] = strs[i];
col_size[p->ret_index] = p->col_index;
continue;
}
/* 在hash表中没找到,生成新的哈希节点,并插入哈希表 */
p = (HaNode *)malloc(sizeof(HaNode));
p->ret_index = ret_index;
p->col_index = 0;
p->wnode = &arr[i];
ret[p->ret_index] = (char **)malloc(sizeof(char *) * strsSize);
ret[p->ret_index][p->col_index++] = strs[i];
col_size[p->ret_index] = p->col_index;
hash_insert(hash_table, p);
ret_index++;
}
free(vist);
free(arr);
hash_exit(hash_table, LEN);
free(hash_table);
*columnSizes = col_size;
*returnSize = ret_index;
return ret;
}
/* 方法一:
* 时间复杂度O(N*N),遍历全部残次,当遍历到当前位置单词时,使用该位置后的所有单词和当前位置单词相比较;
* 相同则插入旧的位置,否则构建新的位置;
* 注意这里需要使用key进行优化,每次两个单词进行比较,首先比较key;
* 每次比较不同的时候,不用比较整个hash字母表了,否则会超时
*/
char*** groupAnagrams_bak(char** strs, int strsSize, int* returnSize, int** columnSizes) {
int i, j;
Node *arr = (Node *)malloc(sizeof(Node) * strsSize);
bool *vist = (bool *)malloc(sizeof(bool) * strsSize);
char *** ret = (char ***)malloc(sizeof(char**) * strsSize);
int *col_size = (int *)malloc(sizeof(int) * strsSize);
int ret_index = 0;
int col_index = 0;
HaNode **hash_table = (HaNode **)malloc(sizeof(HaNode *) * LEN);
HaNode *p = NULL;
int key;
hash_init(hash_table, LEN);
memset(arr, 0, sizeof(Node) * strsSize);
for(i=0; i