1071 Speech Patterns (25 分)

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

Can1:"..."  不是因为Can1是演讲者而不算can,而是题目定义的单词是字母数字组成的字符(alphanumerical characters),can1不是can,所以不算。人名+引号不是输入格式,要是的话肯定会说明的。所有的一行输入都是演讲内容,都是要统计的,一个string变量可以接受一行1048576多个字符。for循环遍历最后一个单词别忘记处理

简化代码的api:

isalpha(c) 是否是英文字母

isalnum(c) 是否是字母数字

isdigit(c) 是否是数字

isupper(c) 是否是大写字母

islower(c) 是否是小写字母

isspace(c) 是否是空格

 

#include<bits/stdc++.h>
using namespace std;
map<string,int> Hash;
char low(char c){
if(isupper(c)) return c+32;
return c;
}
int main(){
char c,a[100];
string temp,ans,in;
int num=0,Max=0;
getline(cin,in);
for(int i=0;i<in.length();i++){
c=in[i];
if(isalnum(c)) a[num++]=low(c);
if(!isalnum(c)||i==in.length()-1){//最后一个单词不能漏了
if(num>0){
a[num]='\0';temp=a;
if(Hash.find(temp)==Hash.end()) Hash[temp]=1;
else Hash[temp]++;
if(Hash[temp]>Max||Hash[temp]==Max&&temp<ans){
ans=temp;
Max=Hash[temp];
}
num=0;
}
}
}
cout<<ans<<" "<<Max;
return 0;
}