牛客网题解 | 单词识别

单词识别

一、题目链接

单词识别

二、题目

三、代码

cpp 复制代码
#include <iostream>
using namespace std;
#include <string>
#include <map>
#include <set>
typedef pair<string, int> Word;
class Compare 
{
  public:
    bool operator()(const Word& left, const Word& right) const 
    {
        // 次数从大到小排序
        // 如果次数相同,再按照单词字典序排序
        return (left.second > right.second) ||
               (left.second == right.second && left.first < right.first);
    }
};
int main() 
{
    string s;
    while (getline(cin, s)) 
    {
        map<string, int> m;
        string temp;

        // 分割单词,采用map统计每个单词出现的次数
        for (size_t i = 0; i < s.size(); ++i) 
        {
            if (s[i] == ' ' || s[i] == ',' || s[i] == '.') 
            {
                // 一个单词解析结束
                if (temp != "")
                    m[temp]++;
                temp = "";
            } 
            else 
            {
                // 注意:题目已说明不区分大小写,那么A和a算是一个单词,故需要将大小写统一
                temp += tolower(s[i]);
            }
        }

        // 将map中的<单词,次数>放到set中,并按照次数升序,次数相同按照字典序规则排序
        set<Word, Compare> s(m.begin(), m.end());

        // 将本次统计到的结果按照要求输出
        for (auto& e : s)
            cout << e.first << ":" << e.second << endl;
        cout << endl;
    }
    return 0;
}
相关推荐
罗湖老棍子2 小时前
荒岛野人(信息学奥赛一本通- P1637)(洛谷-P2421)
算法·数论·枚举·裴蜀定理·扩展欧几里得·扩展中国剩余定理
Ruannn(努力版)2 小时前
Patient/public-facing dashboards-prototype dashboard display
笔记
朝朝辞暮i2 小时前
C++ 第 40 章:ROS2 Publisher + Timer + Subscriber + Callback + Executor 完整闭环
开发语言·c++·算法·ros2
400分2 小时前
具身智能系列之从零到「机械臂会放试管」:π0.5 VLA 真机部署完全指南【第一节】
算法
小宋10212 小时前
一套服务托管多个 LoRA:适配器加载、租户隔离与热切换实战
大数据·人工智能·算法
Rosanci2 小时前
Codex 下载与本地部署实战:从安装到运行全流程指南
开发语言·前端·算法·chatgpt·codex
我爱工作&工作love我3 小时前
P14358 [CSP-J 2025] 座位
算法
旖旎夜光3 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
朝朝辞暮i3 小时前
C++ 第 38 课:线程、SingleThreadedExecutor、MultiThreadedExecutor、Callback Group
开发语言·c++·算法·ros2
(Charon)3 小时前
【C++面试】互斥锁与读写锁:使用场景、实现原理与写饥饿问题
c++·算法