题解 | #单词识别#

单词识别

https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0

思路:使用两次map进行计数和排序,第一次map用来统计不同的单词出现的次数。注意最后一个单词要把'.'去掉,大写的字母要转换成小写的字母。
第二次的multimap用来将单词出现的次数按照降序排列,因为出现次数可能会有重复的所以这里使用multimap。同时降序排序需要回传一个仿函数greater

#include <iostream>
#include <string>
#include <map>
#include <functional>
using namespace std;

void to_uppercase(string& s)
{
    for( auto& e : s)
    {
        if(e >= 'A' && e <='Z')
        {
            e += 32;
        }
    }
}
int main() 
{
    string s;
    map<string,int> countmap;
    while( cin>> s)
    {
        if(s.back() == '.')
            s.pop_back();
        to_uppercase(s);
        countmap[s]++;
    }
    multimap<int,string,greater<int>> sortmap;
    for(auto& e : countmap)
    {
        sortmap.insert(make_pair(e.second,e.first));
    }
    auto it = sortmap.begin();
    while(it != sortmap.end())
    {
        cout<<it->second<<":"<<it->first<<endl;
        it++;
    }
}
全部评论

相关推荐

投递阿里巴巴控股集团等公司7个岗位 >
点赞 评论 收藏
转发
3 收藏 评论
分享
牛客网
牛客企业服务