【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d267
目錄
【方法-1】array
#include <iostream>
#include <map>
using namespace std;
int main() {
int T;
cin >> T;
string s;
getline(cin, s); //混用cin與getline,先清除cin之後的緩衝區
while (T--) {
getline(cin, s);
int a[26] = {}; //大小寫字母不分
int mx = 0;
for (int i = 0; i < s.size(); i++) {
int idx = -1;
if (s[i] >= 'A' and s[i] <= 'Z') {
idx = s[i] - 'A';
}
if (s[i] >= 'a' and s[i] <= 'z') {
idx = s[i] - 'a';
}
if (idx >= 0) {
a[idx]++;
mx = max(mx, a[idx]);
}
}
for (int i = 0; i < 26; i++) {
if (a[i] == mx) {
cout << (char)('a' + i);
}
}
cout << "\n";
}
return 0;
}
【方法-2】map
#include <iostream>
#include <map>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
string s;
cin >> n;
getline(cin, s);
while (n--){
getline(cin, s);
map<char,int> mp;
int mx = 0;
for (int i = 0; i < s.size(); i++){
if (s[i] >= 'a' && s[i] <= 'z'){
mp[s[i]]++;
mx = max(mx, mp[s[i]]);
} else if (s[i] >= 'A' && s[i] <= 'Z'){
s[i] = 'a' + (s[i] - 'A');
mp[s[i]]++;
mx = max(mx, mp[s[i]]);
}
}
for (auto i: mp){
if (i.second == mx){
cout << i.first;
}
}
cout << "\n";
}
return 0;
}
Python code (credit: Amy Chou)
n = int(input())
for i in range(n):
s = input()
dic = {}
for c in s:
if not c.isalpha():
continue
c = c.lower()
dic[c] = dic.get(c, 0) + 1
mx = max(dic.values())
for c in sorted(dic.keys()):
if dic[c] == mx:
print(c, end="")
print()