本文主要是介绍【PAT】1071. Speech Patterns (25)【map容器的使用】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
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?
翻译:对于同一个单词的同义词,每个人都有一种偏爱。举个例子,一些人喜欢用”the police”, 但是另外的人可能更喜欢用”the cops”。通过模仿这种习惯可以帮助缩小演讲者的身份,举个例子,当需要证实网络背后是否仍是同一个人的时候很有用。
INPUT FORMAT
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].
翻译:每个输入文件包含一组测试数据。对于每组输入数据,包括一行不超过1048576个字符长度的文本,直到 ‘\n’时结束。输入至少包含一个字母或数字,即在[0-9 A-Z a-z]范围内的字符。
OUTPUT FORMAT
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容器中,如果Max小于当前单词的个数或等于当前单词个数但字符串S字典序大于当前单词就更新。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<map>
#include<algorithm>
#define INF 99999999
using namespace std;
map<string,int> mp;
int Max=0;
string S;
char s[1048580];
int main(){gets(s);int length=strlen(s);string a;int flag=0;for(int i=0;i<length;i++){if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')||(s[i]>='0'&&s[i]<='9')){if(s[i]>='A'&&s[i]<='Z')s[i]=s[i]-'A'+'a';a.push_back(s[i]);flag=1;if(i==length-1){mp[a]++;if(Max<mp[a]||Max==mp[a]&&S>a){Max=mp[a];S=a;}a.clear();flag=0; }}else if(flag==1){mp[a]++;if(Max<mp[a]||Max==mp[a]&&S>a){Max=mp[a];S=a;}a.clear();flag=0;}}printf("%s %d\n",S.c_str(),Max);return 0;
}
这篇关于【PAT】1071. Speech Patterns (25)【map容器的使用】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!