题解:UVA11577 Letter Frequency

· · 题解

::::info[简要题意]{open} 给出多组字符串,你需要输出每个字符串中出现次数最多的字母(小写输出),如果有多个,则按字典序输出。

输入可能包含大写字母,但是也要计入字母输出次数。

字符串中间可能有空格。 ::::

::::info[思路]{open}

因为字符串中间可能有空格,所以我们需要整行输入,使用 getline

考虑使用 map 作为桶。

把字符串的字母全部放进桶中。

处理完字符串后找到出现次数最多的字母,最后按字典序输出。 ::::

::::success[代码]

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define itn int
#define ull unsigned long long
int T;
string s;
int main(){
    //ios::sync_with_stdio(0);
    //cin.tie(0);cout.tie(0); 这个注释删了就不能用 getchar() 了
    cin>>T;
    getchar();
    while(T--){
        getline(cin,s);
        //cout<<s<<"\n";
        unordered_map<char,int>mp;
        for(int i=0;i<s.size();i++){
            if(s[i]<='z'&&s[i]>='a')mp[s[i]]++;
            if(s[i]<='Z'&&s[i]>='A')mp[s[i]-'A'+'a']++;
        }
        int maxx=0;
        for(char i='a';i<='z';i++){
            maxx=max(maxx,mp[i]);
        }
        for(char i='a';i<='z';i++){
            if(mp[i]==maxx)cout<<i;
        }
        cout<<"\n";
    }
    return 0;
}

/*
`                       4    000      4
                       44   0   0    44
x   x  y   y  x   x    44   0   0    44
x   x  y   y  x   x   4 4   0   0   4 4
 x x   y   y   x x    4 4   0   0   4 4
  x     y y     x    4  4   0   0  4  4
 x x    y y    x x   44444  0   0  44444
x   x    y    x   x     4   0   0     4
x   x    y    x   x     4    000      4
       yy
*/

::::