题解 | #单词识别#

单词识别

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:55
点赞 评论 收藏
分享
06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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