1071 Speech Patterns
People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.
Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?
Input Specification:
Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return \n. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].
Output Specification:
For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a “word” is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.
Note that words are case insensitive.
Sample Input:
Can1: "Can a can can a can? It can!" • 1
Sample Output:
can 5
思路
- 遍历给定的字符串,将字符串拆分成单词放入哈希表进行统计。
- 遍历哈希表,找到出现数量最多的单词。注意,这里如果出现数量相同的单词,取字典序更小的那个。
- 输出出现数量最多的单词以及数量。
代码
#include<bits/stdc++.h> using namespace std; //判断是否为合法字符 bool check(char x) { if (x >= '0' && x <= '9') return true; if (x >= 'a' && x <= 'z') return true; if (x >= 'A' && x <= 'Z') return true; return false; } //将大写转换成小写 char to_lower(char x) { if (x >= 'A' && x <= 'Z') x = 'a' + x - 'A'; return x; } int main() { string x; getline(cin, x); unordered_map<string, int> hash; //将每个单词都放入哈希表中,进行统计 for (int i = 0; i < x.size(); i++) if (check(x[i])) { string res = ""; while (i < x.size() && check(x[i])) res += to_lower(x[i++]); hash[res]++; } //找到出现最多的单词 string ans; int cnt = -1; for (auto t : hash) if (t.second > cnt || t.second == cnt && t.first < ans) { ans = t.first; cnt = t.second; } cout << ans << " " << cnt << endl; return 0; }