题解 | #字符串排序#(输入输出+字符串+自定义排序)

字符串排序

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

解题思路

1.遍历字符串使用无序map保存非字母字符的位置及其元素,使用vector<pair<char, int>>保存字母元素及其位置,然后在sort函数基础上自定义排序即可;

代码

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

bool isAlpha(char ch){
    return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z');
}

int main(){
    string s;
    getline(cin, s);
    int n = s.size();
    vector<pair<char, int>> v; //存储大小写英文字母及其位置
    unordered_map<int, char> f; //存储其他字符及其位置
    for(int i = 0; i < n; i++){
        if(isAlpha(s[i])){
            v.push_back({s[i], i});
        }
        else{
            f[i] = s[i];
        }
    }
    sort(v.begin(), v.end(), [&](pair<char, int>& p1, pair<char, int>& p2){
        char c1 = p1.first, c2 = p2.first;
        if('A' <= c1 && c1 <= 'Z') c1 += 32;
        if('A' <= c2 && c2 <= 'Z') c2 += 32;
        if(c1 == c2) return p1.second < p2.second; //按输入顺序排序
        return c1 < c2; //按字符大小排序
    });
    for(int i = 0, j = 0; i < n; i++){
        if(f.count(i)){
            cout << f[i];
        }
        else{
            cout << v[j].first;
            j++;
        }
    }
    return 0;
}
全部评论

相关推荐

屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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