加qq1126137994 微信:liu1126137994 一起学习更多技术!!!
题目:
给你一个原始字符串,根据该字符串内每一个字符串出现的次数,按照ASCII码递增的排序重新调整输出。
举例:
eeefgghh
则每种字符出现的次数分别是:
(1).eee 3次
(2).f 1次
(3).gg 2次
(4).hhh 3次
重新输出后的字符串如下:
efghegheh
编程实现上述功能:
提示:
(1)原始字符串中仅可能出现字符与数字
(2)注意区分字符的大小写
思路:
不同的字符与数字出现的次数可能为多次,可以利用哈希表原理,生成一个大小为128的数组,数组里面对应的值的下标,代表原始字符串中出现的字符的ASCII码的小,数组的值,代表相应字符串出现的次数。刚好打印数组的下标字符,打印一次,数组对应的值减1,直到减为0则说明出现多次的字符已经全部输出完成!
#include <iostream>
#include <string>using namespace std;//求数组(哈希表)中值出现次数最多的下标,用于循环多少次
int max_count(int count[], int n)
{int max_count = 0;for (int i = 1; i < n; i++){if (count[i]>count[max_count]){max_count = i;}}return max_count;
}int main()
{char str[1000];char* p = str;gets(str);int count[128];for (int i = 0; i < 128; i++){count[i] = 0;}for (; *p != 0; p++){//求数组中对应下标(即字符串的字符的值)出现的次数count[*p]++;}int num = max_count(count,128);for (int i = 0; i < num; i++){for (int j = 0; j < 128; j++){if (count[j] != 0){printf("%c",j);count[j]--;}}}//getchar();return 0;
}
或者:
#include <iostream>
#include <string>using namespace std;int max_count(int count[], int n)
{int max_count = 0;for (int i = 1; i < n; i++){if (count[i]>count[max_count]){max_count = i;}}return max_count;
}int main()
{string str;getline(cin,str,'\n');int len = str.size();int count[128];for (int i = 0; i < 128; i++){count[i] = 0;}for (int i=0; i<len; i++){count[str[i]]++;}int num = max_count(count,128);for (int i = 0; i < num; i++){for (int j = 0; j < 128; j++){if (count[j] != 0){printf("%c",j);count[j]--;}}}//getchar();return 0;
}