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!"
Sample Output:
can 5
代码长度限制
16 KB
时间限制
300 ms
内存限制
64 MB
#include <iostream>
#include <unordered_map>
using namespace std;
bool checkChar(char c){
if(c >= 'a' && c <= 'z') return true;
if(c >= 'A' && c <= 'Z') return true;
if(c >= '0' && c <= '9') return true;
return false;
}
int main() {
string s1;
getline(cin,s1);
unordered_map<string,int> map;
int j = 0;
string temp;
for(int i = 0; i < s1.length(); i++){
if(s1[i]>='A'&&s1[i]<='Z') s1[i] = tolower(s1[i]);
if(checkChar(s1[i])){
temp += s1[i];
}
if(!checkChar(s1[i])|| i == s1.length()-1){
if(!temp.empty()) map[temp]++;
temp = "";
}
}
string MaxItem;
int max = 0;
for(auto item : map){
// cout << item.first << item.second << endl;
if(item.second > max){
MaxItem = item.first;
max = item.second;
}
if(item.second == max && item.first < MaxItem){
MaxItem = item.first;
max = item.second;
}
}
cout << MaxItem << ' ' << max << endl;
return 0;
}
总结
1. tolower的使用,要求是char,返回的也是char 实现字符大写转小写。
2. 字符串截取的思路,以及使用map来存储字符串出现的次数。
3. 字符串长度,str.length() 字符串判空 str.empty()