题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include <iostream> #include <map> #include <vector> using namespace std; char toCap(char c) { if (c >= 'a' && c <= 'z') { return c - 'a' + 'A'; } else { return c; } } bool isLetter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } int main() { string s; while (getline(cin, s)) { map<char, vector<char>> map; string s_out = s; vector<bool> letter(s.size(), false); for (int i = 0; i < s.size(); i++) { if (isLetter(s[i])) { letter[i] = true; map[toCap(s[i])].push_back(s[i]); } } auto it = map.begin(); int j = 0; for (int i = 0; i < s.size(); i++) { if (letter[i]) { if (j == it->second.size()) { it++; j = 0; } s_out[i] = it->second[j]; j++; } } cout << s_out; } } // 64 位输出请用 printf("%lld")
使用map(或二维数组)保存对应位置上的输入字母,再按照这个位置输出。