1071 Speech Patterns (25分)
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
题目描述:求给定的字符串中,出现次数最多的单词,这些单词由数字、大小写字母组成。
输入:一串字符串
输出:出现最多的单词及出现次数
解题思路:getline函数读取所有字符,要在读入所有字符后加一个字符'.',当读入的最后一个字符是数字或者大小写字母时,比较容易将最后一个单词切分出来。接着,根据特殊字符来切分单词,并用map<string,int>来记录每个单词出现的次数。在记录的同时,我们也可以把答案顺便找出来。用ans和count两个量简单比较就行了。
注意:最后一个测试点就是卡在最后一个单词有没有正确切分并计数。
#include<bits/stdc++.h>
using namespace std;
map<string,int> p;
int main()
{
string s, t="";
getline(cin,s);
s += '.';//不加最后一个测试点会错
int l = s.length();
string ans="";
int count = 0;
for(int i=0; i<l; i++){
if(s[i]>='0'&&s[i]<='9'){
t += s[i];
}
else if(s[i]>='A'&&s[i]<='Z'){
t += s[i]-'A'+'a';
}
else if(s[i]>='a'&&s[i]<='z'){
t += s[i];
}
else{
if(t.length()!=0) p[t]++;
if(p[t]==count){
ans = t < ans ? t : ans;
}
else if(p[t]>count){
count = p[t];
ans = t;
}
t = "";
}
}
cout << ans << " " << count << endl;
return 0;
}