题解 | 字符串排序

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

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

int main()
{
    char s[1010] = {0}, t[1010] = {0};
    fgets(s, sizeof(s), stdin);
    s[strcspn(s, "\n")] = '\0';
    int count = 0;

    // 提取字母
    for (int i = 0; s[i] != '\0'; i++)
    {
        if (isalpha(s[i]))
            t[count++] = s[i];
    }

    // 字母排序 使用稳定的冒泡排序
    for (int i = 0; i < count - 1; i++)
    {
        for (int j = 0; j < count - 1 - i; j++)
        {
            if (tolower(t[j]) > tolower(t[j + 1]))
            {
                char temp = t[j];
                t[j] = t[j + 1];
                t[j + 1] = temp;
            }
        }
    }

    // 输出
    int k = 0;
    for (int i = 0; s[i] != '\0'; i++)
    {
        if (isalpha(s[i]))
            printf("%c", t[k++]);
        else
            printf("%c", s[i]);
    }
    
    return 0;
}

将需要排序的字母提出来,然后对字母使用稳定排序(因为不要求比大小写),之后再按照原样输出就行

全部评论

相关推荐

鱼专:别投了,我看到有人点了第二个链接投递,还没退出界面,不合适的邮件就发过来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务