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
分析:对字符串进行处理,统计出现最多的单词。
注意点:
(1)将单词化为小写字母来统计;
(2)利用map来统计某个单词出现的个数。
#include<iostream>
#include<map>
#include<vector>
#include<string>
using namespace std;
int main(){
map<string,int> m; //记录单词出现的次数
int i = 0;
char t;
vector<char> input;
while(scanf("%c",&t)){
if(t == '\n')
break;
input.push_back(t);
}
input.push_back('\n');
vector<char>::iterator it = input.begin();
int len = input.size();
int begin = -1,end = -1; //记录一个单词的起止位置
int max = 0;
string s_temp;
for(i=0; i<len; i++){
if(input[i] == '\n') break;
//如果是字母或者数字就继续输入
if( isalpha(input[i]) || isdigit(input[i])){
if(!islower(input[i])){
input[i] = tolower(input[i]);
}
if(begin == -1){
begin = i;
}
end = i;
}
//如果不是字母或数字
else{
if( begin != -1 ){
string s(it+begin, it+end+1);
m[s] ++;
if(m[s] > max || ( m[s] == max && s<s_temp )){
max = m[s];
s_temp = s;
}
}
begin = -1;
}
}
//最后一个单词
if(begin != -1){
string s(it+begin, it+end+1);
m[s] ++;
if(m[s] > max || ( m[s] == max && s<s_temp )){
max = m[s];
s_temp = s;
}
}
if(max != 0)
cout<<s_temp<<" "<<max<<endl;
return 0;
}