Day8 出现频率最高的字母 -卡码网C++基础课
题目链接:出现频率最高的字母
题目描述
给定一个只包含小写字母的字符串,统计字符串中每个字母出现的频率,并找出出现频率最高的字母,如果最高频率的字母有多个,输出字典序靠前的那个字母。
输入描述
包含多组测试数据,每组测试数据占一行。
输出描述
有多组输出,每组输出占一行。
输入示例
2
abcdeef
aabbccddeeff
输出示例
e
a
点击查看代码
#include<iostream>
#include<string>
using namespace std;
int main(){
int n;
string s;
while(cin >> n){
while(n--){
cin >> s;
int count[26] = {0};
for(int i = 0;i < s.size();i++){
count[s[i]-'a']++;
}
int flag = 0;
char result;
for(int i = 0;i < 26;i++){
if(count[i] > flag){
flag = count[i];
result = 'a' + i;
}
}
cout << result << endl;
}
}
return 0;
}
小结
运用哈希表思想,建立一个大小为26的int 数组,初始为0
再遍历每行字符串,通过将 'a' - 'z' 与数组下标0-25对应,对数组对应下标的数组值加一
最后遍历数组,与现有的对比,找到频率最高的

浙公网安备 33010602011771号