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;
}

浙公网安备 33010602011771号