首页 > 电脑

编写一个函数,

更新时间2020-12-15 04:35:28

字符串统计
(1)编写一个函数,对一个字符串进行如下统计:统计字符串中各不同字符出现的次数,并按各字符出现的频率按降序排列,若频率相同,则按其在原字符串中出现的顺序排列输出。
例如:"tree" 对应的输出为"etr","abcabdebabde" 对应的输出为"badec"
(2)主函数中输入字符串,通过上述函数的调用,完成字符串统计功能。

你要用什么语言做这个?以下是我用C++写的参考

#include <iostream> #include <vector> #include <algorithm> using namespace std; struct DATA { char c; int count; } ; typedef vector <DATA> V_DATA; class data_finder { public: data_finder(const int val):m_data(val) {} bool operator ()(const V_DATA::value_type &value) { return value.c == m_data; } private: int m_data; }; bool compare(const DATA &a,const DATA &b) { return a.count>b.count; } int tosort(const char *s) { char c; DATA t_d; V_DATA data; V_DATA::iterator it=data.end(); while(c=*s++) { t_d.count=1; t_d.c=c; it=find_if(data.begin(),data.end(),data_finder(c)); if (it == data.end()) data.push_back(t_d); else { it->count++; t_d.count=it->count; } } sort(data.begin(),data.end(),compare); for(it = data.begin(); it !=data.end(); it++ ) cout << it->c  ; } int main() { char s[10001]; cin >> s; tosort(s); return 0; }

测试结果符合你的要求:

编写一个函数,

上一篇:excel把固定数字随机排列

下一篇:java模拟图书管理系统的功能,创建图书实体类,使用集合作为数据容器。需求: