题解 | #查找兄弟单词#

查找兄弟单词

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

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

typedef struct{
    char str[16];
    char flag;
}W_NODE;
//判断兄弟字串
int checkBSwap(char *test, char *s)
{
    char temp[16] = {0};
    int findBFlag = 0;
    int count = 0;
    int len = strlen(s);
    if(strlen(test) != len)
        return 0;
    if(0 == strcmp(test,s))
        return 0;

    strcpy(temp,test);
    for(int i= 0; i < len; i++)
    {
        for(int j = 0; j < len; j++)
        {
            if(s[i] == temp[j]){
                temp[j] = 0;
                count++;
                break;
            }
        }
    }
    if(count == len)
        return 1;
    else
        return 0;
} 
//判断循环偏移字串
int checkB(char *test, char *s)
{
    int len = strlen(s);
    int findFlagi = 1;
    int findBFlag = 0;
    if(strlen(test) != len)
        return 0;
    for(int i = 1; i < len; i++)
    {
        for(int j = 0; j < len; j++)
        {
            if(test[j] != s[(i+j)%len])
                findFlagi = 0;
        }
        if(1 == findFlagi){
            findBFlag = 1;
            return findBFlag;
        }
        
        findFlagi = 1;
    }

    return findBFlag;
}

int main() {
    int wCount = 0;
    W_NODE Ws[1000] = {0};
    char x[16] = {0};
    int k = 0;
    scanf("%d",&wCount);

    int idx = 0;
    char ch = 0;
    getchar();
    int i = 0;
    while(idx < wCount){
        ch = getchar();
        if(' ' == ch)
        {
            i = 0;
            idx++;
        }else{
            Ws[idx].str[i++] = ch;
        }
    }
    i = 0;
    while(' ' != (ch = getchar())){
        x[i++] = ch;
    }
    scanf("%d",&k);
    //字典排序
    W_NODE temp;
    for(int i = 0; i < wCount; i++)
    {
        for(int j = i; j < wCount; j++)
        {
            if(strcmp(Ws[i].str,Ws[j].str) > 0)
            {
                temp = Ws[i];
                Ws[i] = Ws[j];
                Ws[j] = temp;
            }
        }
    }
    idx = 0;
    int outIndex = 0;
    int findXFlag = 0;
    for(int i = 0; i < wCount; i++){
        if(1 == checkBSwap(Ws[i].str, x))
        {
            Ws[i].flag = 1;
            idx++;
            if(k == idx){
                outIndex = i;
                findXFlag = 1;
            }
        }
    }
    printf("%d\n",idx);
    if(1 == findXFlag)
        printf("%s",Ws[outIndex].str);
    return 0;
}

全部评论
关键是查找兄弟,和按字母顺序排序,查找兄弟可以按照单词排除法,按字母顺序排序可以用strcmp函数
点赞 回复 分享
发布于 03-09 11:17 广东

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务