leetcode-49.字母异位词分组

1. 题目

leetcode-49.字母异位词分组_第1张图片

2. 解答

#include 
#include 
#include 

#define MAX_STRLEN (10000 + 1)
#define MAX_CHARLEN (100 + 1)

char map[128] = {0};
char map_start[128] = {0};

void solve(char input[MAX_STRLEN][MAX_CHARLEN], int num)
{
    int visited[num];
    for (int i = 0; i < num; i++) visited[i] = 0;

    for (int i = 0; i < num; i++) {

        if (visited[i]) continue;

        printf("[");

        memset(map_start, 0, 128);
        for (int j = 0; j < strlen(input[i]); j++) {
            map_start[input[i][j]]++;
        }

        printf("%s", input[i]);

        visited[i] = 1;

    
        for (int j = i; j < num; j++) {
            if (j == num -1) printf("]");
            if (visited[j] || i == j) continue;

            memset(map, 0, 128);

            for (int k = 0; k < strlen(input[j]); k++) {
                map[input[j][k]]++;
            }

            if (memcmp(map, map_start, 128) == 0) {
                visited[j] = 1;
                printf(", %s", input[j]);
            }
        }
    }

    printf("]\n");
}

int main()
{
    char strs[MAX_STRLEN];

    fgets(strs, MAX_STRLEN, stdin);

    strs[strlen(strs) - 1] = '\0';

    int num = 0;

    char input[MAX_STRLEN][MAX_CHARLEN] = {{0}};

    char *token = strtok(strs, "[, \"\"]");

    while(token) {
        printf("token:%s\n", token);
        memcpy(input[num], token, strlen(token));
        token = strtok(NULL, "[, \"\"]");
        num++;
    }

    solve(input, num);

    return 0;

}

运行结果:

G3-3579:~/data/source/leetcode$ gcc 49.c
G3-3579:~/data/source/leetcode$ ./a.out 
["eat", "tea", "tan", "ate", "nat", "bat"]
token:eat
token:tea
token:tan
token:ate
token:nat
token:bat
[eat, tea, ate][tan, nat][bat]]
G3-3579:~/data/source/leetcode$ ./a.out 
["a"]
token:a
[a]]

你可能感兴趣的:(编程题或面试题,leetcode,linux,算法)