题解 | #单词识别#

单词识别

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与快排进行最后的顺序排列

全部评论

相关推荐

09-22 09:42
门头沟学院 Java
牛客37185681...:马德,我感觉这是我面过最恶心的公司,一面是两个女hr,说什么实习前几个月属于试用期,试用期过了才能转成正式实习生,我***笑了,问待遇就是不说,问能不能接受全栈,沙币公司
如果可以选,你最想去哪家...
点赞 评论 收藏
分享
09-29 00:03
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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