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
思路:用map<string,int>来储存并计数 找到最大出现次数最大的那个就是OK 没有什么坑点!
AC参考代码:
#include <iostream>
#include <map>
using namespace std;
string lowerIt(string s){
for(int i=0;i<s.size();i++){
if(s[i]>='A'&&s[i]<='Z'){
s[i] = s[i]-'A'+'a';
}
}
return s;
}
map<string,int> myMap;
int main()
{
string s;
getline(cin,s);
string temp = "";
for(int i=0;i<s.size();i++){
if((s[i]>='0'&&s[i]<='9') || (s[i]>='a'&&s[i]<='z') || (s[i]>='A'&&s[i]<='Z')){
temp +=s[i];
}else if(temp!=""){
temp = lowerIt(temp);
myMap[temp]++;
temp = "";
}
if((i==s.size()-1) && ((s[i]>='0'&&s[i]<='9') || (s[i]>='a'&&s[i]<='z') || (s[i]>='A'&&s[i]<='Z'))){
if(temp!=""){
temp = lowerIt(temp);
myMap[temp]++;
temp = "";
}
}
}
map<string,int>::iterator it;
string result = (*myMap.begin()).first;
int num = (*myMap.begin()).second;
for(it=myMap.begin();it!=myMap.end();it++){
if((*it).second>num){
num = (*it).second;
result = (*it).first;
}
}
cout<<result<<" "<<num;
return 0;
}