题解 | #字符统计#

字符统计

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

sort 函数只能用于支持随机访问迭代器的容器,而 unordered_map 并不支持随机访问迭代器,因此不能直接对 u_map 进行排序。可以将 u_map 转化为 vector 容器后再进行排序。

#include <cctype>
#include <iostream>
#include<bits/stdc++.h>
#include <unordered_map>
#include <vector>
using namespace std;

int main() {
    string str;
    while (cin >> str) {
        set<char>m_set;
        unordered_map<char, int>u_map;
        for (auto& ch : str) {
            if (u_map.find(ch) == u_map.end()) {
                u_map.emplace(ch, 1);
            } else {
                u_map[ch]++;
            }

        }
        vector<pair<char, int>>vec(u_map.begin(), u_map.end());
        sort(vec.begin(), vec.end(),
        [](const pair<char, int>& a, const pair<char, int>& b) {
            if (a.second == b.second) {
                return a.first < b.first;
            } else
                return a.second > b.second;
        });
        for (auto& ch : vec) {
            cout << ch.first;
        }
    }

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务