题目难度:中等
OJ链接:单词识别_牛客题霸_牛客网 (nowcoder.com)
题目描述:
输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,次数一样的按照单词小写的字典序排序输出,要求能识别英文单词和句号。
输入描述:输入为一行,由 若干个单词 和 句号 组成。
输出描述:输出格式参见样例。
示例:
输入: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
解题思路:
#include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
void words_parse(string& words)
{
map<string, int> count_map; // 定义map,用来统计出单词出现次数,以及排单词的字典序
// 遍历英文句子words中的每一个字符(除了句尾的句号)
// 若遇到空格就分解出单词,然后构造键值对<单词,单词出现次数>,插入count_map中
string tmp; // 保存当前分解出的单词
for(size_t i = 0; i < words.size() - 1; i++)
{
if(words[i] == ' ') // 单词分隔符
{
count_map[tmp]++; // 插入count_map中
tmp = "";
}
else // 正常的单词
{
// 如果是大写字母,则转成小写字母
if(words[i] >= 'A' && words[i] <= 'Z')
{
words[i] += 'a' - 'A';
}
tmp += words[i];
}
}
// 因为最后一个单词后面没有空格,所以遍历结束后,还需要将最后一个单词插入count_map中
count_map[tmp]++;
// 在不破坏单词字典序的情况下,对单词出现次数排降序
// 用count_map中的元素,构造键值对<单词出现次数,单词>插入sort_map中
multimap<int, string, greater<int>> sort_map;
for(auto& e : count_map)
{
sort_map.insert(make_pair(e.second, e.first));
}
// 输出排序结果
for(auto& e : sort_map)
{
cout << e.second << ":" << e.first << endl;
}
}
int main()
{
// 输入英文句子
string words;
getline(cin, words);
// f
words_parse(words);
return 0;
}