题目链接:
https://pintia.cn/problem-sets/994805260223102976/problems/994805280817135616
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
#include <string.h>
#include <map>
using namespace std;
int main(){
map<char,int > m;
string s;
getline(cin,s);
for(int i=0;i<s.size();i++){
if(s[i]>='A'&&s[i]<='Z'){
m[s[i]+32]++;
}
else if(s[i]>='a'&&s[i]<='z'){
m[s[i]]++;
}
}
int max_=0;//最大值
char ch;//记录最大值字母
for(map<char,int >::iterator it=m.begin();it!=m.end();it++){
if(max_<it->second){
max_=it->second;
ch=it->first;
}
}
cout<<ch<<" "<<max_;
}
注意:
map的greater用法:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
#include <string.h>
#include <map>
using namespace std;
int main(){
map<char,int ,greater<char> > m;
string s;
getline(cin,s);
for(int i=0;i<s.size();i++){
if(s[i]>='A'&&s[i]<='Z'){
m[s[i]+32]++;
}
else if(s[i]>='a'&&s[i]<='z'){
m[s[i]]++;
}
}
for(map<char,int ,greater<char> >::iterator it=m.begin();it!=m.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
}
输出:(对key值降序排序),由此可知:less,是升序排序
二刷:
#include <iostream>
#include <cstdio>
#include <string>
#include <map>
using namespace std;
int main(){
map<char,int> mp;
string str;
getline(cin,str);
int len=str.size();
for(int i=0;i<len;i++){
if(str[i]>='A'&&str[i]<='Z'){
str[i]+=32;
mp[str[i]]++;
}
else if(str[i]>='a'&&str[i]<='z')
mp[str[i]]++;
}
int max_=0;
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
//map会自动按key值排序,只要判断大于即可,因为如果存在相同的value值,则max_只取排序靠前的,符合题意,所以不必加下面那个map for循环
if(max_<it->second)
max_=it->second;
}
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
//map会自动按key值排序,
if(max_==it->second){
cout<<it->first<<" "<<it->second;
break;
}
}
}