牛客 KY264 单词识别

51 阅读1分钟

输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,次数一样的按照单词小写的字典序排序输出,要求能识别英文单词和句号。

输入描述: 输入为一行,由若干个单词和句号组成

输出描述: 输出格式参见样例。

输入:
A blockhouse is a small castle that has four openings through which to shoot.
输出:
a:2
blockhouse:1
castle:1
four:1
has:1
is:1
openings:1
shoot:1
small:1
that:1
through:1
to:1
which:1

示例1

#include <iostream>
using namespace std;
#include <string>
#include<map>
#include<vector>
#include<algorithm>
//重写cmp,按降序排序
bool cmp(const pair<string, int>& p1, const pair<string, int>& p2)
{
    return p1.second > p2.second;
}
int main() {
    string s;
    //默认按string升序(字典序)排序
    map<string, int> m;
    //从流中读取字符串到s中(默认遇到'/n'结束)
    getline(cin, s);
  
        for (int i = 0, j = 0; i < s.size(); i++)
        {
            if (s[i] == ' ' || s[i] == ','|| s[i] == '.')
            {
                //截取单词
                string t = s.substr(j, i - j);
                //判断单词首字母是否是大写,如果是,转换为小写
                if (isupper(t[0]))
                    t[0] = tolower(t[0]);
                //j更新至下一个单词首字母
                j = i + 1;
                //首次出现的单词插入,次数置为0后++,不是首次出现,次数++
                m[t]++;
            }

        }
        vector<pair<string, int>> v;

    for (auto& e : m)
    {
        v.push_back(e);
    }
    //使用稳定的排序,确保其相对顺序不变
    stable_sort(v.begin(), v.end(), cmp);
    for (auto& e : v)
    {
        cout << e.first << ":" << e.second << endl;
    }
    return 0;
}


在这里插入图片描述

在这里插入图片描述