本题考查字符处理,包括对单词的理解,是很常见的一道题。很容易想到用map存储,找到数量最多、单词词典顺序较小的那个词需要用到map的自定义排序。
map的自定义排序是通过将map转换成vector<pair<temp1 temp2>>,然后使用sort函数处理的。关于map的排序可以参看
https://blog.csdn.net/weixin_34212189/article/details/85584916
写的比较详细和全面。
下面贴出AC代码
#include<stdio.h>
#include<map>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
bool cmp(pair<string, int> a, pair<string, int> b)
{
if (a.second != b.second)
{
return (a.second > b.second);
}
else
{
return (a.first < b.first);
}
}
int main()
{
map<string, int> words;
char c;
string word;
while (scanf("%c", &c))
{
if ((c >= '0'&&c <= '9') || (c >= 'a'&&c <= 'z') || (c >= 'A'&&c <= 'Z'))
{
// 全部转换成小写来存储
if (c >= 'A'&&c <= 'Z')
{
c = 'a' + c - 'A';
}
word += c;
}
else
{
if (word.size() != 0)
{
if (words.count(word) == 0)
{
words[word] = 1;
}
else
{
words[word]++;
}
word.clear();
}
if (c == '\n')
{
break;
}
}
}
vector<pair<string, int>> wordVec(words.begin(), words.end());
sort(wordVec.begin(), wordVec.end(), cmp);
printf("%s %d\n", wordVec.front().first.c_str(), wordVec.front().second);
return 0;
}