当前位置:网站首页>力扣练习——61 根据字符出现频率排序
力扣练习——61 根据字符出现频率排序
2022-08-10 10:59:00 【qq_43403657】
61 根据字符出现频率排序
1.问题描述
给定一个字符串,请将字符串里的字符按照出现的频率降序排列,如果频率相同,则按照字符的ASCII码升序排列。
示例 1:
输入:
“tree”
输出:
“eert”
解释:
'e’出现两次,'r’和’t’都只出现一次。
因此’e’必须出现在’r’和’t’之前,而且’r’比’t’的ASCII码小。
示例 2:
输入:
“cccaaa”
输出:
“aaaccc”
解释:
'c’和’a’都出现三次。因此按照字符升序排列,'a’在’c’前。
示例 3:
输入:
“Aabb”
输出:
“bbAa”
解释:
'A’和’a’被认为是两种不同的字符,并且’A’的ASCII码比’a’小
2.输入说明
输入一个字符串
3.输出说明
输出一个字符串,字符串中字符的顺序请参考以上说明。
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;
}
边栏推荐
- 什么是抽象类
- [Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists
- CodeChef STMRRG String Merging (dp)
- 负载均衡原理分析与源码解读
- mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
- 推荐6个自媒体领域,轻松易上手
- Open Office XML 格式里如何描述多段具有不同字体设置的段落
- 从产品维度来看 我们为什么不能完全信任Layer2?
- MLX90640 红外热成像仪测温传感器 手机 APP 软件 RedEye 连接详细
- 内存问题难定位,那是因为你没用ASAN
猜你喜欢

AutoCAD Map 3D功能之一暴力处理悬挂点(延伸)

Gold, nine, silver and ten job-hopping seasons: technical interview questions and answers on Alibaba, Baidu, JD.com, and Meituan

1-IMU参数解析以及选择

从源码角度分析UUID的实现原理

电脑怎么设置屏幕息屏时间(日常使用分享)

内存问题难定位,那是因为你没用ASAN

Short video software development - how to break the platform homogenization

OneFlow源码解析:算子指令在虚拟机中的执行

从脚本到剪辑,影像大师亲授的后期制作秘籍

振弦传感器及核心VM系列振弦采集模块
随机推荐
POJ 3101 Astronomy (数学)
【无标题】
Codeforces 814 C. An impassioned circulation of affection (dp)
Three-phase 380V rectified voltage
Some tips for using Unsafe
Weilai-software development engineer side record
POJ 3101 Astronomy (Mathematics)
从产品角度看 L2 应用:为什么说这是一个游乐场?
不止跑路,拯救误操作rm -rf /*的小伙儿
Gartner reiterates the important value of 'data weaving'
mysql5.7安装部署-yum安装
第5章相似矩阵及二次型(4)
谷歌数据中心发生“电力事故”造成 3 人受伤
8月份DB-Engines 数据库排行榜最新战况
负载均衡原理分析与源码解读
Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
Emulate stm32 directly with proteus - the programmer can be completely discarded
如何使用工程仪器设备在线监测管理系统
What is an abstract class
从源码角度分析UUID的实现原理