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;
}

算法解释

  1. 字符计数: 使用一个 pair<char, int> 类型的数组 charCount 来存储每个字符及其出现的次数。数组大小为 128,可以容纳 ASCII 码表中的所有字符。代码使用 memset 将数组初始化为 0。
  2. 排序: 使用 sort 函数对 charCount 数组进行排序,排序规则由 cmp 函数定义。cmp 函数首先比较两个 pairsecond 成员,如果相等则比较 first 成员。排序结果为降序排列。
  3. 输出: 遍历 charCount 数组,输出出现次数非零的字符。

总结

该代码实现了简单的字符计数排序算法,能够统计字符串中每个字符出现的次数并按降序排列。通过修改 cmp 函数的逻辑,可以实现不同的排序规则。

注意: 代码中使用的 pair 类型是标准库中的一个模板类,用于存储两个不同类型的值。firstsecondpair 类的成员变量。

C++ 字符计数排序算法:统计字符串字符出现次数并按降序排列

原文地址: https://www.cveoy.top/t/topic/nYCx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录