题解 | #查找兄弟单词#

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int cmp(const void* x, const void* y)
{
    const char* a = x;
    const char* b = y;

    return *a - *b > 0 ? 1 : -1;
}
int IsBro(char* str3, char* str4)
{
    char str1[1000];
    char str2[1000];

    strcpy(str1,str3);
    strcpy(str2,str4);

    if (strcmp(str1, str2) == 0)
    {
        return 0;
    }
    qsort(str1, strlen(str1), 1, cmp);
    qsort(str2, strlen(str2), 1, cmp);

    if (strcmp(str1, str2) != 0)
    {
        return 0;
    }
    return 1;
}

int main() {
    int n = 0;
    int i = 0, j = 0;
    int index = 0;
    scanf("%d", &n);

    //放字典单词
    char* str[1000] = { 0 };
    for (int i = 0; i < 1000; i++)
    {
        str[i] = (char*)calloc(100, sizeof(char));
    }
    while(i < n)
    {
        scanf("%s", str[i]);
        i++;
    }
    
    //输入正经单词
    char word[100] = {0};
    scanf("%s", word);
    //输入要的第k个字典单词的序号
    int k = 0;
    scanf("%d", &k);

    //与字典单词比较+整理兄弟单词
    char* bro[1000] = { 0 };
    for (int i = 0; i < 1000; i++)
    {
        bro[i] = (char*)calloc(100, sizeof(char));
    }
    int isBroCount = 0;
    for(i = 0; i < n; i++)
    {
        if(IsBro(str[i], word))
        {
            isBroCount++;
            strcpy(bro[index++],str[i]);
        }
    }


    printf("%d\n", isBroCount);
    //对字典单词进行排序   x!
    //对兄弟单词进行排序   √!
    for(i = 0; i < isBroCount; i++)
    {
        for(j = 0; j < isBroCount-1-i; j++)
        {
            if(strcmp(bro[j],bro[j+1]) >= 0)
            {
                char tmp[1000];
                strcpy(tmp, bro[j]);
                strcpy(bro[j], bro[j+1]);
                strcpy(bro[j+1], tmp);
            }
        }
    }
    if(IsBro(bro[k-1], word))
    {
        puts(bro[k-1]);
    }
    
    return 0;
}

全部评论

相关推荐

投递网易雷火等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务