【C语言刷LeetCode】49. 字母异位词分组(M)

【给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:


    所有输入均为小写字母。
    不考虑答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。】

这道题挺难的,关键点在于memcmp,太久没使用这个函数了,很难想到这点。

一开始异位词很容易想到哈希去匹配,毕竟小写字母就26个,一个int字符就有32位,所以包含对应的字符就把对应的bit位置1。然后根据这个int字符是否相等,把对应字母归到一起。

但实际这种方法是错误的,没有考虑重复字母。

所以每个单词的哈希值需要大小为26的数组来表达,如何比较每个单词对应的数组是否相等就只能用memcmp,直接内存比较。

接着就是malloc申请内存(多次),memset(很有必要),strcpy(千万不要自己造轮子,有库函数就用)。

void Setbitword(char *str, char *bitword) {
    int i = 0;
    int intstr = 0;
    
    while(str[i] != '\0') {
        intstr = str[i] - 'a';
        bitword[intstr]++;
        i++;
    }
}

char *** groupAnagrams(char ** strs, int strsSize, int* returnSize, int** returnColumnSizes){
    char bitword[strsSize][26] ;
    int *flagword;
    int i;
    int j;
    char ***retarr;
    int line = 0;
    int col = 0;
    int len;

    flagword = (int *)malloc(sizeof(int) * strsSize);

    memset(bitword, 0 ,strsSize * 26);
    
    returnColumnSizes[0] = (int *)malloc(sizeof(int) * strsSize);
    
    retarr = (char ***)malloc(sizeof(char **) * strsSize);

    for (i = 0; i < strsSize; i++) {
        Setbitword(strs[i], bitword[i]);
        flagword[i] = 0;
    }
    
    for (i = 0; i < strsSize; i++) {
        if (flagword[i] == 1) {
            continue;
        }

        retarr[line] = (char **)malloc(sizeof(char *) * strsSize);
        col = 0;

        for (j = i; j < strsSize; j++) {

            if ((flagword[j] == 0) && (!memcmp(bitword[i], bitword[j], 26))) {
                flagword[j] = 1;
                
                len = strlen(strs[j]);
                retarr[line][col] = (char *)malloc(sizeof(char) * (len + 1));
                strcpy(retarr[line][col], strs[j]);
                col++;
            }
        }
        
        returnColumnSizes[0][line] = col;
        line++;
    }
    
    *returnSize = line;
    
    return retarr;
}
发布了102 篇原创文章 · 获赞 17 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/jin615567975/article/details/104323691