Speech Patterns
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
题意
给出一行字符串,仅包含’a’-‘z’、‘A’-‘Z’、‘0’-'9’的连续字符串为有效字符串,要求统计并打印出现次数最多的有效字符串及其出现次数,若出现次数相同,则输出字典序较小的字符串,注意不区分大小写(以小写为准)。
思路
主要利用map映射来处理,逐个读入字符,若为有效字符则并入string变量temp中(注意要将大写字符转化为小写字符),若为无效字符,则停止读入,将值为temp的key存入map中,并令对应的value值+1。最后选择value最大的一组输出即可。
代码实现
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> mp;
void createMap()
{
string temp;
char ch;
while (cin.get(ch)) // 依次读入字符进行处理
{
if (!((ch >= '0' && ch <= '9') // 若为无效字符,则将已有的temp存入map
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')))
{
if (temp.length()) // 注意值为空的key不能存入map,不然会干扰最后排序
mp[temp]++;
temp.clear(); // 每次存入map后要讲temp清空
}
else if (ch >= 'A' && ch <= 'Z') // 大写字符转小写
{
ch = ch - 'A' + 'a';
temp += ch;
}
else // 有效字符直接并入temp
temp += ch;
if (ch == '\n') // 字符串结束判断
break;
}
}
int main()
{
string key;
int value = 0;
map<string, int>::iterator it;
createMap();
for (it = mp.begin(); it != mp.end(); it++)
if (it->second > value) // 由于map的key已按字典序排序,只要选出value最大的第一组即可,因此不能用>=
{
key = it->first;
value = it->second;
}
cout << key << " " << value;
}