当前位置:网站首页>Buckle Exercise - 61 Sort by frequency of characters
Buckle Exercise - 61 Sort by frequency of characters
2022-08-10 11:34:00 【qq_43403657】
61 根据字符出现频率排序
1.问题描述
给定一个字符串,请将字符串里的字符按照出现的频率降序排列,如果频率相同,则按照字符的ASCII码升序排列.
示例 1:
输入:
“tree”
输出:
“eert”
解释:
'e’出现两次,'r’和’t’都只出现一次.
因此’e’必须出现在’r’和’t’之前,而且’r’比’t’的ASCII码小.
示例 2:
输入:
“cccaaa”
输出:
“aaaccc”
解释:
'c’和’a’都出现三次.So in ascending order of characters,'a’在’c’前.
示例 3:
输入:
“Aabb”
输出:
“bbAa”
解释:
'A’和’a’被认为是两种不同的字符,并且’A’的ASCII码比’a’小
2.输入说明
输入一个字符串
3.输出说明
输出一个字符串,Please refer to the above description for the order of characters in the string.
4.范例
输入
Aabb
输出
bbAa
5.代码
#include<iostream>
#include<map>
#include<string>
#include<unordered_map>
#include<algorithm>
using namespace std;
bool cmp(pair<char, int> a, pair<char, int>b)
{
return a.second == b.second?a.first<b.first:a.second>b.second;//该题目中最关键的部分,注意写法!
}
string OrderbyChar(string s)
{
//给定一个字符串,请将字符串里的字符按照出现的频率降序排列,如果频率相同,则按照字符的ASCII码升序排列.
string res;//结果字符串
unordered_map<char, int>hash;//记录每个字符出现次数
vector<pair<char, int> > v;//使用pair记录对应关系
for (auto c : s)//遍历字符串
hash[c]++;
for (auto it : hash)
v.emplace_back(it);//直接将每个hash元素插入v中
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < v.size(); i++)
{
while (v[i].second--)
res += v[i].first;
}
return res;
}
int main()
{
string s;
cin >> s;
string res = OrderbyChar(s);
cout << res << endl;
return 0;
}
边栏推荐
猜你喜欢
Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
1-IMU参数解析以及选择
MLX90640 红外热成像仪测温传感器 手机 APP 软件 RedEye 连接详细
怎么加入自媒体,了解这5种变现模式,让账号快速变现
Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
CPU多级缓存与缓存一致性
Spss-多元回归案例实操
第5章相似矩阵及二次型(4)
英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞
2022年裁员潮,失业程序员何去何从?
随机推荐
In August the DB list latest scores - database Engines
微信小程序,全局变量一个地方改变了其他地方的状态也跟着改变。
WeChat applet, global variables change in one place and the state in other places also changes.
从源码角度分析UUID的实现原理
力扣练习——61 根据字符出现频率排序
LeetCode_443_压缩字符串
A case of violent parameter tuning in machine learning
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
The brave rice rice, does not fear the brush list of 】 list has a ring
L2 applications from a product perspective: why is it a playground?
flask-restplus接口地址404问题
Nocalhost - 让云原生时代的开发更高效
Short video software development - how to break the platform homogenization
【机器学习】浅谈正规方程法&梯度下降
越折腾越好用的 3 款开源 APP
[E-commerce operation] Do you really understand social media marketing (SMM)?
LeetCode_152_乘积最大子数组
Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
POJ 1026 Cipher (Permutation Groups)
【电商运营】你真的了解社交媒体营销(SMM)吗?