leetcode.49字母异位词分组(C语言)

记录

/**
 * 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().
 */
int cmp(const void *a,const void *b)
{
     return(*(char *)a-*(char *)b);
}


char *** groupAnagrams(char ** strs, int strsSize, int* returnSize, int** returnColumnSizes){
    int i;
    char ** strsCpy = (char **)malloc(sizeof(char *)*strsSize);
//1、先将每个单词按字母顺序排序存放在一个新的空间strsCpy里;
    for(i=0; i<strsSize; i++){
        strsCpy[i] = (char *)malloc(sizeof(char)*100);
        strcpy(strsCpy[i],strs[i]);
        qsort(strsCpy[i],strlen(strsCpy[i]),sizeof(strsCpy[i][0]),cmp);
    }
//2、mask数组用来标记是否是字母异位词,初始值赋为-1;
    int mask[strsSize];
    memset(mask,-1,sizeof(mask));
    
    char *** ret = (char ***)malloc(sizeof(char **)*strsSize);
    returnColumnSizes[0] = (int *)malloc(sizeof(int )*strsSize);

    *returnSize = 0;

    int k,j;
//3、legnth数组记录ret中每一行单词的个数,同returnColumnSizes[0],初始值0;
    int length[strsSize];
    memset(length,0,sizeof(length));

//遍历一次strs
    for(i=0; i<strsSize; i++){
        k=0;
        while(mask[k] >= 0){
            
            if(0 == strcmp(strsCpy[i],strsCpy[mask[k]])){     
                //printf("[%d][%d] ",k,length[k]);

                ret[k][length[k]] = (char *)malloc(sizeof(char)*(strlen(strs[i])+1));
                strcpy(ret[k][length[k]],strs[i]);
                //printf("%s\n",ret[k][length[k]]);
                length[k]++;
                break;
            }
            k++;
        }
        if(mask[k] < 0){
            mask[k]=i;
            //printf("[%d][0] ",k);
            ret[k] = (char **)malloc(sizeof(char *)*strsSize);
            ret[k][0] = (char *)malloc(sizeof(char)*(strlen(strs[i])+1));
            strcpy(ret[k][0],strs[i]);
            //printf("%s\n",ret[k][0]);
            length[k]++;
            (*returnSize)++;
            
        }

    }
    for(j=0; j<strsSize; j++)
        returnColumnSizes[0][j] = length[j];
    //printf("%d",*returnSize);
    return ret;
}

你可能感兴趣的:(Leetcode算法)