6.4 map的常见用法详解
6.4 map的常见用法详解
http://codeup.hustoj.com/contest.php?cid=100000599
A Speech Patterns (25)

题目释义
给定字符串,输出其中出现频率最高的单词及出现次数。【忽略字符大小写,输出一律大写】
若有频率一样高的单词,则根据字典序输出最小的那个单词。
⚠️单词包括字母和数字,遇到非字母和数字或行尾时即代表单词的结束。
题目解析
要读入一行,可使用gets然后赋值给string,或直接getline(cin, s);
用map建立string到int的映射,因为map键不重复且自动从小到大排序,故无需在意频率相同时输出的问题。
代码
#include <cstdio>
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool alphanumerical(char &a) {
if (a >= 'A' && a <= 'Z') {
a += 32;
return true;
}
if (a >= 'a' && a <= 'z') return true;
if (a >= '0' && a <= '9') return true;
return false;
}
int main() {
char str[1048600];
string s, subs;
while (gets(str)) { //或getline(cin,s);
s = str;
map<string, int> mp;
for (int i = 0; i < s.length(); i++) {
bool temp = alphanumerical(s[i]);
if (temp) subs += s[i];
if (!temp || i == s.length() - 1) {
if (subs.length() != 0) mp[subs]++;
subs.clear();
}
}
string ans;
int temp = 0;
for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++) {
if (it->second > temp) {
ans = it->first;
temp = it->second;
}
}
printf("%s %d\n", ans.c_str(), temp);
}
return 0;
}
本文作者:Joey-Wang
本文链接:https://www.cnblogs.com/joey-wang/p/14541174.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步