GESP编程共123题,本题是整站第1465题,已经有人完成了本题,加油!
在文本处理中,统计单词出现的频率是一个常见的任务。现在,给定 n 个单词,你需要找出其中出现次数最多的单词。在本题中,忽略单词中字母的大小写(即 Apple
、apple
、APPLE
、aPPle
等均视为同一个单词)。
请你编写一个程序,输入 n 个单词,输出其中出现次数最多的单词。
第一行,一个整数 n,表示单词的个数;
接下来 n 行,每行包含一个单词,单词由大小写英文字母组成。
输入保证,出现次数最多的单词只会有一个。
输出一行,包含出现次数最多的单词(输出单词为小写形式)。
输入 #1
6 Apple banana apple Orange banana apple
输出 #1
apple
对于所有测试点,1≤n≤100,每个单词的长度不超过 30,且仅由大小写字母组成。
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
map<string, int> cnt;
int mx = -1;
for (int i = 1; i <= n; i++) {
string s; cin >> s;
transform(s.begin(), s.end(), s.begin(), ::tolower);
cnt[s]++;
mx = max(mx, cnt[s]);
}
for (auto it : cnt) {
if (it.second == mx) {
cout << it.first << '\n';
break;
}
}
return 0;
}
知识点解析:
使用 map<string, int>
统计小写单词频率。
遍历输入单词,转换为小写后更新计数。
遍历哈希表,找到频率最高的单词。
参考代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
map<string, int> cnt;
string s;
while (n--) {
cin >> s;
transform(s.begin(), s.end(), s.begin(), ::tolower);
cnt[s]++;
}
int max_count = 0;
string ans;
for (auto& [word, count] : cnt) {
if (count > max_count) {
max_count = count;
ans = word;
}
}
cout << ans;
return 0;
}
核心:哈希表统计与字符串处理。
本站题目仅供学习,GESP版权归CCF所有,如有侵权请联系删除。站长陈老师QQ及微信:208234。