题解 | #字符串排序# C++桶排序

字符串排序

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

#include <iostream>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    string in;
    getline(cin, in);
    string alphas = "";
    for (char c : in) {
        if (isalpha(c)) {
            alphas.push_back(c);
        }
    }

    vector<vector<int>> bucket(26, vector<int>(0));
    for (char c : alphas) {
        if (islower(c)) {
            bucket[c - 32 - 'A'].push_back(c);
        } else {
            bucket[c - 'A'].push_back(c);
        }
    }
    alphas.clear();
    for (int i = 0; i < 26; ++i) {
        if (bucket[i].size() > 0) {
            for (char c : bucket[i]) {
                alphas.push_back(c);
            }
        }
    }
    int j = 0;
    for (int i = 0; i < in.size(); ++i) {
        if (isalpha(in[i])) {
            in[i] = alphas[j++];
        }
    }
    cout << in << endl;
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务