题解 | 字符串排序

字符串排序

https://www.nowcoder.com/practice/d9aa3894d3aa4887843a85d26daa4437

#include<bits/stdc++.h>
#define py puts("YES")
#define pn puts("NO")
using namespace std;



void solve(){
    string txt;
  
 // while循环不断读入文本
    while(getline(cin, txt)){
	  
	  //先用一个向量存储所有的英文字母,有更优美的写法。
        vector<pair<char,int>> words;
        int idx = 0;
        for(auto &ch : txt){
            if(('a' <= ch and ch <= 'z') or
            ('A' <= ch and ch <= 'Z')) words.push_back({ch, idx++});
        }
	  
      //对所有的英文字母进行编码,让A的值和a的值相同,这是后面排序的依据之一
        string alpha = "abcdefghijklmnopqrstuvwxyz";
        map<char, int> kv;
        for(int i = 0; i < size(alpha); i++){
            kv[alpha[i]] = i;
            kv[toupper(alpha[i])] = i;
        }
	  
	  //sort()内部使用lambda表达式来排序,排序的逻辑是:如果字母的值相同,那么位置小的拍在前面(即稳定排序)
	  //如果字母的值不相同,按照字母表出现的顺序来排序
        sort(words.begin(), words.end(), [&](pair<char,int>&a, pair<char,int>&b){
            if(kv[a.first] == kv[b.first]){
                return a.second < b.second;
            }
            return kv[a.first] < kv[b.first];
        });
	  
	  //这里代码的底层逻辑就是把排好序的字母,重新还原到输入的文本txt当中,当然存在更优美的写法。
        reverse(words.begin(), words.end());
        for(int i = 0; i < size(txt); i++){
            if(('a' <= txt[i] and txt[i] <= 'z') or
            ('A' <= txt[i] and txt[i] <= 'Z')){
                txt[i] = words.back().first;
                words.pop_back();
            }
        }
	  //输出答案
        cout << txt << endl;
    }

}

int main() {
    int testCase = 1;
    //cin >> testCase;
    while(testCase--) solve();
    return 0;
}

全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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