692. 前K个高频单词 、KY264 单词识别

692. 前K个高频单词 - 力扣(LeetCode)

//#include<set>
class Solution {
public:
    //仿函数
    struct compare
    {
        bool operator()(const pair<string,int>& kv1,const pair<string,int>& kv2)
        {
                return kv1.second > kv2.second;
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        //插入(在插入过程中,已经按照字典序排好序了)
        map<string,int> count_map;
        for(auto e : words)
        {
            count_map[e]++;
        }
        
        //排序
        vector<pair<string,int>> v(count_map.begin(),count_map.end()); 
        stable_sort(v.begin(),v.end(),compare());
        
        //拿到前K个
        vector<string> ret;
        for(int i = 0; i<k; ++i)
        {
            ret.push_back(v[i].first);
        }
        
        
        return ret;

    }
};

单词识别_牛客题霸_牛客网 (nowcoder.com)

#include <algorithm>
#include <cctype>
#include <iostream>
#include<map>
#include<string>
#include<vector>
#include <sstream>

using namespace std;

struct compare
{
    bool operator()(const pair<string,int>& kv1 ,const pair<string,int>& kv2)
        {
            return kv1.second > kv2.second;
        }
};

int main() {
    string s;
    getline(std::cin,s,'.');

    //变小字母
    for(auto& c : s)
    {
        c = tolower(c);
    }
    
    map<string,int> count_map;
    istringstream iss(s);
    string word;

    //插入单词并计数
    while(iss >> word)
    {
        count_map[word]++;
    }

    //放入vecotr
    vector<pair<string,int>> v(count_map.begin(),count_map.end());   

    //按照统计次数进行降序
    stable_sort(v.begin(), v.end(),compare());
    
    //输出
    for(auto e : v)
    {
        cout<<e.first<<":"<<e.second<<endl;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二十5画生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值