题目
不同的人对描述同一种事物的同义词的偏爱程度可能不同。
例如,在说警察时,有人喜欢用 the police
,有人喜欢用 the cops
。
分析说话方式有助于确定说话者的身份,这在验证诸如和你线上聊天的是否是同一个人十分有用。
现在,给定一段从某人讲话中提取的文字,你能确定他的最常用词吗?
输入格式
输入共一行,包含一个字符串,以回车符 \n
终止。
输出格式
共一行,输出最常用词以及其出现次数。
如果常用词有多个,则输出字典序最小的那个单词。
注意,单词在输出时,必须全部小写。
单词是指由连续的字母和数字构成的,被非字母数字字符或行首/行尾分隔开的,连续序列。
单词不区分大小写。
数据范围
输入字符串长度不超过 1048576,且至少包含一个大小写字母或数字。
输入样例:
1
Can1: "Can a can can a can? It can!"
输出样例:
1
can
题解
解法1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream> #include <map> using namespace std; int main() { string s1; getline(cin, s1); string word; map<string, int> words; for (auto c : s1) { if ((c >= '0' && c <= '9') || (c >= 'a') && c <= 'z') { word += tolower(c); } else { if (!word.empty()) { words[word]++; } word.clear(); } } if (!word.empty()) { words[word]++; } int max_count = 0; string max_word; for (auto w : words) { if(w.second > max_count) { max_count = w.second; max_word = w.first; } } cout << max_word << ' ' << max_count << endl; return 0; }
使用哈希集合的解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream> #include <unordered_map> using namespace std; int main() { string s1; getline(cin, s1); string word; unordered_map<string, int> hash; for (auto c : s1) { if ((c >= '0' && c <= '9') || (c >= 'a') && c <= 'z') { word += tolower(c); } else { if (!word.empty()) { hash[word]++; } word.clear(); } } if (!word.empty()) { hash[word]++; } int max_count = 0; string max_word; for (auto w : hash) { if(w.second > max_count || (w.second == max_count && w.first < max_word)) { max_count = w.second; max_word = w.first; } } cout << max_word << ' ' << max_count << endl; return 0; }