题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
#include <iostream> #include <string> using namespace std; void count(const string str) { //记录各个字符的个数,前十记录数字,后二十六记录小写字母 int num[36] = { 0 }; for (int i = 0; i < str.length(); i++) { if (('0' <= str[i]) && (str[i] <= '9')) { num[str[i] - '0']++; } else { if (('a' <= str[i]) && (str[i] <= 'z')) { num[str[i] - 'a' + 10]++; } } } //按顺序输出 for (int i = 0; i < 36; i++) { //记录字符最多数量及其下标 int m = 0; int mi = 0; //遍历一次,找出最多的字符 for (int j = 0; j < 36; j++) { if (num[j] > m) { m = num[j]; mi = j; } } //如果最大为0,说明是空串或已输出完毕 if (m == 0) { return; } else { //将下标转化为字符输出 if (mi < 10) cout << (char)('0' + mi); else cout << (char)('a' + mi - 10); //清除数据 m = 0; num[mi] = 0; } } } int main() { string str; while (cin >> str) { // 注意 while 处理多个 case count(str); } } // 64 位输出请用 printf("%lld")