知识点字符串排序哈希
描述
对于给定的由小写字母和数字构成的字符串 s,统计出现的每一个字符的出现次数,按出现次数从多到少排序后依次输出。特别地,如果出现次数相同,则按照 ASCII 码由小到大排序。
输入描述:
在一行上输入一个长度为 1≦len(s)≦103、由小写字母和数字构成的字符串 s。
输出描述:
在一行上输出一个字符串,代表按频次统计后的结果。
示例1
输入:
aaddccdc
输出:
cda
说明:
在这个样例中,字符 ‘c’ 和 ‘d’ 出现的次数最多,均为 3 次,而前者 ASCII 码更小,因此先输出。
cc方法0:暴力枚举+冒泡排序
/hj102_char_cnt_00_vio_00.cc
cpp
// 暴力枚举法
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string GetRes(const string & s)
{
vector<pair<char, int>> res;
for (const char & ch : s) {
bool flag = true;
for (pair<char, int> & cur : res) {
if (cur.first == ch) {
cur.second++;
flag = false;
break;
}
}
if (flag) {
res.push_back({ch, 1});
}
}
// 根据统计进行排序,字符出现次数多拍前
for (int i = 0; i < res.size() - 1; ++i) {
for (int j = i + 1; j < res.size(); ++j) {
if (res[i].second < res[j].second) {
pair<char, int> tmp({res[i].first, res[i].second});
res[i] = {res[j].first, res[j].second};
res[j] = {tmp.first, tmp.second};
}
}
}
// 根据ASCII码进行排序,ASCII较小排前
for (int i = 0; i < res.size() - 1; ++i) {
for (int j = i + 1; j < res.size(); ++j) {
if (res[i].second == res[j].second && res[i].first > res[j].first) {
swap(res[i], res[j]);
}
}
}
string str = "";
for (const auto & cur : res) {
str.push_back(cur.first);
}
return str;
}
int main()
{
string s = "";
while (getline(cin, s)) {
cout <<GetRes(s) << endl;
}
return 0;
}
cc方法1:stl
/hj102_char_cnt_01_stl_00.cc
cpp
// stl
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
string GetRes(const string & s)
{
map<char, int> mp;
for (const char c : s) {
mp[c]++;
}
// 用迭代器范围初始化一个vector
vector<pair<char, int>> res(mp.begin(), mp.end());
// 上文mp已经根据ASCII进行了排序,所以只需要对次数进行排序
// 使用稳定排序,当次数一样时,会保持原来的先后关系,及mp中的ASCII升序
stable_sort(res.begin(), res.end(), [] (const pair<char, int> & a, const pair<char, int> & b) {
return a.second > b.second;
});
string str = "";
for (const auto & cur : res) {
str.push_back(cur.first);
}
return str;
}
int main()
{
string s = "";
while (getline(cin, s)) {
cout <<GetRes(s) << endl;
}
return 0;
}
cc方法2:stl
/hj102_char_cnt_01_stl_01.cc
cpp
// stl
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
string GetRes(const string & s)
{
map<char, int> map1;
// 为什么是string?因为字符数相同时根据ASCII顺序直接组成string
map<int, string> map2;
// map1存放字符到数量的映射,此过程也是进行字符的ASCII排序
for (int i = 0; i < s.size(); ++i) {
map1[s[i]]++;
}
// 根据字符统计数量进行排序,因为上文map1已经对字符的ASCII进行排序,所以下文中的字符ASCII排序是天然排好的
for (auto it = map1.begin(); it != map1.end(); ++it) {
// 为什么是push_back?
// 因为字符数相同时map只有一个键值,不同字符公用这个键值,
// 直接根据ASCII顺序组成字符统计数相同的string
map2[it->second].push_back(it->first);
}
string str = "";
for (auto it = map2.rbegin(); it != map2.rend(); ++it) {
str += it->second;
}
return str;
}
int main()
{
string s = "";
while (getline(cin, s)) {
cout <<GetRes(s) << endl;
}
return 0;
}