题目:
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=Can 不是同一个单词。输出时要求输出成小写字母。
思路:
1、需要辨认是否为单词,并以单词存入map<string,int >变量中。当第一次出现时要令其计数为1,否则自增1即可。
2、由于是一句话,用'\n'结束,则可用字符变量进行读取,且 char c=getchar()!='\n'为结束条件。
#include<cstdio>
#include<string>
#include<map>
using namespace std;
int main ( ){
char c;
string s;
map<string,int> cnt;
while((c=getchar())!= '\n'){
if(c>='0'&&c<='9'||c>='A'&&c<='Z'||c>='a'&&c<='z'){
if(c>='A'&&c<='Z'){
c=c-'A'+'a';
}
s+=c;
}else if(s.size()!=0){
if(cnt.find(s)!=cnt.end()) cnt[s]++;
else cnt[s]=1;
s.clear();
}
}
if(s.size()!=0){//必要的,如有input:"sde\n"则读到'\n'时会退出,但还没有将s读入cnt中
if(cnt.find(s)!=cnt.end()) cnt[s]++;
else cnt[s]=1;
s.clear();
}
map<string,int> ::iterator it=cnt.begin();
int Max=0;
for(;it!=cnt.end();++it){
if(Max<it->second){
Max=it->second;
s=it->first;
}
}
printf("%s %d\n",s.c_str(),Max);
return 0;
}
如有新想法会及时更新