分数 25
全屏浏览题目
切换布局
作者 HOU, Qiming
单位 浙江大学
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<bits/stdc++.h>
using namespace std;
string res;
map<string,int>mp;
int mcnt;
int main(){
string s;
getline(cin,s);
for(int i=0;i<s.size();i++)//转为小写
if(s[i]>='A'&&s[i]<='Z')s[i]=s[i]+32;
for(int i=0;i<s.size();i++){//取单词在对应哈希表位置加一
int j=i;
string temp;
while(s[j]>='a'&&s[j]<='z'||s[j]>='0'&&s[j]<='9')temp+=s[j++];//取出一个单词
if(temp.size())mp[temp]++;//是一个单词则在对应位置+1
if(mp[temp]>mcnt)mcnt=mp[temp];//若大于最大数字则更新最大数字
i=j;
}
int flag=0;
for(auto it:mp){//遍历哈希表
if(!flag&&it.second==mcnt){//拿到第一个大小为最大值的单词
flag=1;
res=it.first;
}
else if(it.second==mcnt&&it.first<res)res=it.first;//若超过第一次出现的单词出现字数也是最大的并且字典序小于当前记录的单词,则更新单词
}
cout<<res<<' '<<mp[res];//输出
return 0;
}