题解 | #单词识别#

单词识别

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

#include <iostream>
using namespace std;
#include<map>
#include<algorithm>
#include<string>
#include<vector>

struct Compare
{
    bool operator()(const pair<string,int>&a,const pair<string,int>&b)
    {
        return a.second>b.second;//比较的仿函数
    }
};

int main()
{
    string s;
    map<string,int>Map;
    getline(cin,s);//因为有空格,用geiline接收

    char*ch;
    for(int i=0;i<s.size();++i)
    {
        string ss;
        while(s[i]!=' ')
        {
            if(s[i]=='.')
            {
                break;//处理句子末
            }

            ss+=tolower(s[i++]);//记得转换为小写
        }
        Map[ss]++;
    }


    vector<pair<string,int>>arr(Map.begin(),Map.end());
    stable_sort(arr.begin(),arr.end(),Compare());//map容器是帮我们用字典序排好了的,只是不根据数量大小排序,stable_sort稳定的排序,不会影响arr中数量相同的元素的相对位置
    for(auto it:arr)
    {
        cout<<it.first<<":"<<it.second<<endl;
    }
    return 0;
}

我们思路是先提取出单词,然后根据map与快排进行最后的顺序排列

全部评论

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-04 14:23
steelhead:你回的有问题,让人感觉你就是来学习的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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