经典指数          
原因
1394
浏览数
0
收藏数
 

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? 输入描述: 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]. 输出描述: 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. 输入例子: Can1: "Can a can can a can? It can!" 输出例子: can 5

     举报   纠错  
 
切换
1 个答案

这道题其实就是统计单词个数,输出出现次数最多的单词。

首先是分词,按题目要求将句子分成单个词, 然后可以直接使用hash来统计出现的次数。

需要说明的一点是,使用string 作为 map 的key 时,在插入时已经按string的字典序排列好了,所以最后只需要输出第一个次数最多的单词即可。

代码如下:

#include

#include

#include

using namespace std;

int main(){

string str;

getline(cin, str);

str += " "; //为后面便于分词,在最后加上一个空格

map < string,int> hash;

bool isword = false;

int start = 0;

int end = 0;

int max = 0;

for (int i = 0; str[i] != 0; i++)

{

if ((str[i]>='0' && str[i]<='9') || (str[i]>='a' && str[i]<='z')

|| (str[i]>='A' && str[i]<='Z'))

{

if (str[i]>='A' && str[i]<='Z') //转换为小写

str[i] = str[i] - 'A' + 'a';

if (isword == false)

{

start = i;

isword = true;

}

}

else

{

if (isword == true)

{

end = i;

string strtmp = str.substr(start, end-start);

if (hash.find(strtmp) == hash.end()) //计数

hash[strtmp] = 1;

else

hash[strtmp]++;

int tmp = hash[strtmp];

max = max > tmp ? max : tmp; //最多的次数

isword = false;

}

}

}

for (auto it = hash.cbegin(); it != hash.cend(); it++)

{

if (it->second == max) //输出出现次数最多的词

{

cout << (it->first).c_str() << " " << it->second << endl;

break;

}

}

}

 
切换
撰写答案