题解 | #单词识别#

单词识别

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++;
    }
}
全部评论

相关推荐

01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务