C++ 字符计数排序算法:统计字符串字符出现次数并按降序排列
C++ 字符计数排序算法:统计字符串字符出现次数并按降序排列
本文将介绍使用 C++ 代码实现的字符计数排序算法,该算法可以统计字符串中每个字符出现的次数并按降序排列。
代码实现
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(pair<char, int> a, pair<char, int> b) {
if (a.second == b.second) {
return a.first < b.first;
} else {
return a.second > b.second;
}
}
void countChars(char* str) {
pair<char, int> charCount[128];
memset(charCount, 0, sizeof(charCount));
for (int i = 0; str[i] != '0'; i++) {
charCount[str[i]].first = str[i];
charCount[str[i]].second++;
}
sort(charCount, charCount + 128, cmp);
for (int i = 0; i < 128; i++) {
if (charCount[i].second != 0) {
cout << charCount[i].first;
}
}
}
int main() {
char str[100];
cin >> str;
countChars(str);
return 0;
}
算法解释
- 字符计数: 使用一个
pair<char, int>类型的数组charCount来存储每个字符及其出现的次数。数组大小为 128,可以容纳 ASCII 码表中的所有字符。代码使用memset将数组初始化为 0。 - 排序: 使用
sort函数对charCount数组进行排序,排序规则由cmp函数定义。cmp函数首先比较两个pair的second成员,如果相等则比较first成员。排序结果为降序排列。 - 输出: 遍历
charCount数组,输出出现次数非零的字符。
总结
该代码实现了简单的字符计数排序算法,能够统计字符串中每个字符出现的次数并按降序排列。通过修改 cmp 函数的逻辑,可以实现不同的排序规则。
注意: 代码中使用的 pair 类型是标准库中的一个模板类,用于存储两个不同类型的值。first 和 second 是 pair 类的成员变量。
原文地址: https://www.cveoy.top/t/topic/nYCx 著作权归作者所有。请勿转载和采集!