题目链接:点击打开链接
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我的C++代码:
#include<iostream>
#include<map>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
string sentence;
getline(cin, sentence);//输入一句话
map<string, int> word_frequency;//单个单词出现的次数
string word;//单词
int i = 0;
vector<string>vec_word;//存储单词的vector
int max_frequency = 0;//最大出现次数
string most_commonly_word;//出现次数最多的单词
for (i = 0; i <sentence.length(); i++)//把一句话分解成单词组成的vector
{
word= "";
while (isalnum(sentence[i]))//字符是数字或字母
{
if (isupper(sentence[i]))//大写转小写
sentence[i] = tolower(sentence[i]);
word += sentence[i];//得到单个的单词
i++;
}
if (word!= "")
vec_word.push_back(word);//把单词放进vector
}
for (int i = 0; i<vec_word.size(); i++)//把单词放进map
{
word_frequency [ vec_word[i] ]++;//记录每个单词的出现次数
if (max_frequency <word_frequency [vec_word[i]] )//查找出现次数最多的单词
{
max_frequency = word_frequency [vec_word[i]];
most_commonly_word = vec_word [i];
}
}
cout << most_commonly_word << " " << max_frequency;//输出最常见的单词,和出现次数
//system("pause");
return 0;
}