题解 | 字符串排序
字符串排序
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;
}
查看3道真题和解析