题解 | #字符统计#

字符统计

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

#include <iostream>
#include <map>
#include <vector>

using namespace std;

typedef pair<char,int> T;//第一个为字符,第二个指字符出现次数

//按值排序
void SortByValue(map<char, int> &mapHash,  vector<T> &vecHash)
{
    for (auto it = mapHash.begin(); it != mapHash.end(); it++){
        vecHash.push_back(make_pair(it->first, it->second)); //make_pair创建键值对
    }
    
    for (int i = 0; i < vecHash.size(); i++){
        for (int j = i; j < vecHash.size(); j++){
            if (vecHash[i].second < vecHash[j].second){       //value降序排序
                swap(vecHash[i], vecHash[j]);
            }
            else if (vecHash[i].second == vecHash[j].second){ //ASCII码由小到大排序
                if (vecHash[i].first > vecHash[j].first){
                    swap(vecHash[i], vecHash[j]);
                }
            }
        }
    }
}

int main ()
{
    char str;
    map<char, int> mapHash;
    vector<T> vecHash;

    while (cin >> str){
        auto it = mapHash.find(str);  
        if (it != mapHash.end()) {  // 键存在,修改其对应的值  
            it->second += 1;  
        } else {                    // 键不存在,可以选择插入新的键值对  
            mapHash[str] = 1;  
        }
    }

     // 遍历并输出元素  
    SortByValue(mapHash, vecHash);
    for (int i = 0; i < vecHash.size(); i++){
        cout << vecHash[i].first ;
        // cout << " "<< vecHash[i].second << endl; 
    }
    cout << endl;
    return 0;
}

全部评论

相关推荐

2024-12-27 13:08
华南理工大学 Java
蝴蝶飞出了潜水钟丿:多看一眼就会💥
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务