题目来源:PAT (Advanced Level) Practice
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
words:
preference 偏爱 narrow 狭窄的,狭隘的 validating 确证,证实 terminated 停止,终止
insensitive 不敏感的 lexicographically 字典序 continuous 连续的
题意:
给出一行字符串(含有空格),找出出现次数最多的单词并统计其出现次数;字母不区分大小写;
单词定义为字母或数字的连续序列;
思路:
1. 使用geiline输入整个字符串s;
2. 找出字符串中的单词word,并将其加入到map容器mp中去,若word已经在map中存在,则其次数加1,即value+1;
3. 遍历mp中的每一个元素,找出值最大(出现次数最多)的键并输出键和值;
4. 注意字符串s中的最后一个单词也要统计,为了便于统计,在统计之前给字符串s的末尾加上'\0';
5. 字符串s中的字符不区分大小写,但输出单词时需要以小写的形式输出;
//PAT ad 1071 Speech Patterns
#include <iostream>
using namespace std;
#include <map>
int main()
{
string s;
getline(cin,s);
map<string,int> mp;
string t;
s.push_back('\0'); //便于统计上最后一个字符
for(int i=0;i<s.size();i++)
{
if(isalnum(s[i])) //数字或字母
t.push_back(tolower(s[i])); //趁机转化为小写
else
{
if(!t.empty())
{
if(mp.find(t)==mp.end()) //word不存在
mp[t]=1;
else
mp[t]++;
}
t.clear(); //置空
}
}
int ma=0; string index; //ma表示最大值,index表示最大值的键
for(auto w:mp) //遍历所有键值对,寻找最大值的键
if(w.second>ma)
{
ma=w.second;
index=w.first;
}
cout<<index<<" "<<ma<<endl; //输出
}