C++ 单词识别_牛客题霸_牛客网
点击链接即可查看题目: 单词识别_牛客题霸_牛客网
一、题目
描述
输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,次数一样的按照单词小写的字典序排序输出,要求能识别英文单词和句号。
输入描述:
输入为一行,由若干个单词和句号组成
输出描述:
输出格式参见样例。
示例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
二、解题思路以及代码
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include<algorithm>
using namespace std;
class compare
{
public:
bool operator()(const pair<string,int> p1, const pair<string,int> p2)
{
return p1.second > p2.second || (p1.second == p2.second && p1.first < p2.first);
}
};
int main()
{
string s;
map<string,int> countmap;
vector<string> v;
while (getline(cin, s))
{
// 统一转换为小写
for(auto& e : s)
{
if('A' <= e && e < 'a')
e += 'a' - 'A';
}
// 截取单词存在vector
string cur;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '.' || s[i] == ' ')
{
v.push_back(cur);
cur.clear();
}
else
{
cur.push_back(s[i]);
}
}
// 利用map存进去单词,并且按照字典序排序
for(auto& e : v)
{
countmap[e]++;
}
// 存到vector,
vector<pair<string,int>> vp(countmap.begin(),countmap.end());
// 将其按照字典序以及次数排序
sort(vp.begin(), vp.end(),compare());
for(auto& e : vp)
{
cout << e.first << ":"<< e.second << endl;
}
}
return 0;
}
// 64 位输出请用 printf("%lld")