C++ 找出字符串中出现次数最多的字母
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
cin >> s;
vector<int> count(26, 0); // 用于记录每个小写字母出现的次数,初始化为0
// 统计每个小写字母出现的次数
for (char c : s) {
if (islower(c)) {
count[c - 'a']++;
}
}
int maxCount = *max_element(count.begin(), count.end()); // 找出出现次数最多的小写字母的次数
char maxChar = 'z'; // 初始化为字母'z',ASCII码值最大的小写字母
// 找出出现次数最多的小写字母
for (int i = 0; i < 26; i++) {
if (count[i] == maxCount) {
maxChar = max(maxChar, static_cast<char>('a' + i));
}
}
cout << maxChar << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pawz 著作权归作者所有。请勿转载和采集!