华为机试:字符串排序

1.英文字母不分大小写升序排序

2.其他字符保持原位

例:BcdAaAtTypE------>AaABcdEptTy

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;

bool cmp(const char x, const char y) {
    return tolower(x) < tolower(y);
}

int main() {
    string input;
    getline(cin, input);
    string Sort;
    for (char ch : input) {
        if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
            Sort.push_back(ch);
        } else {
            continue;
        }
    }
    stable_sort(Sort.begin(), Sort.end(), cmp);      //要稳定的排序相对顺序才不会变
    string ans;
    auto it = Sort.begin();
    for (char ch : input) {
        if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
            ans.push_back(*it);
            it++;
        } else {
            ans.push_back(ch);
        }
    }
    cout << ans << endl;
    return 0;
}

全部评论
谢谢大哥的教学
点赞 回复 分享
发布于 2023-02-13 20:12 广东
又学得一题
点赞 回复 分享
发布于 2023-02-13 20:00 广东

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
7
分享

创作者周榜

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