题解 | 字符串排序
#include <bits/stdc++.h> using namespace std; bool cmp(char s1, char s2) { if (s1 >= 'A' && s1 <= 'Z')s1 += 32; if (s2 >= 'A' && s2 <= 'Z')s2 += 32; return s1 < s2; }//规定这个的目的是为了能统一比较大小写,如果用默认字典序,则会大写在前,小写在后 bool isWord(char s) { if (s >= 'a' && s <= 'z' || (s >= 'A' && s <= 'Z'))return true; return false; } int main() { string s; while (getline(cin, s)) { string t; int l = s.size(); for (int i = 0; i < l; i++) if (isWord(s[i])) { t += s[i]; } stable_sort(t.begin(), t.end(), cmp); for (int i = 0; i < l; i++) if (!isWord(s[i])) t.insert(t.begin() + i, s[i]); cout << t << endl; } }
本质上就是实现了一个稳定的大小写统一化的排序,大小写统一化我已经讲解明白了,stable_sort即可稳定排序