返回目录
题意
输入一串字符,除了大小写字母和数字外的字符作为分隔符,得到很多单词,求出现次数最多的单词,其中字母不区分大小写,最后按小写输出
样例(可复制)
Can1: "Can a can can a can? It can!"
//output
can 5
注意点
- 使用map<string,int>对出现的单词计数,难点在于得到单词
- 本题使用check检查当前字符是否为有效字符,如果是有效字符则加到word里
#include<bits/stdc++.h>
using namespace std;
bool check(char a){
if(a>='A'&&a<='Z')return true;
if(a>='a'&&a<='z')return true;
if(a>='0'&&a<='9')return true;
return false;
}
int main(){
string s;
getline(cin,s);
int i=0,maxx=0;
map<string,int> count;
while(i<s.size()){
string word;
while(i<s.size()&&check(s[i])){
if(s[i]>='A'&&s[i]<='Z')s[i]+=32;
word+=s[i];
i++;
}
if(word!=""){
if(count.find(word)!=count.end())count[word]++;
else count[word]=1;
}
while(i<s.size()&&!check(s[i]))i++;
}
for(map<string,int>::iterator it=count.begin();it!=count.end();it++){
if(it->second>maxx){
s=it->first;
maxx=it->second;
}
}
cout<<s<<" "<<maxx;
return 0;
}