当前位置:网站首页>力扣练习——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;
}
边栏推荐
- Weilai-software development engineer side record
- [Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
- 用proteus直接仿真stm32-可以完全丢弃编程器
- POJ 2891 Strange Way to Express Integers (扩展欧几里得)
- 【TypeScript】接口类型与类型别名:这两者的用法与区别分别是什么?
- LAXCUS分布式操作系统安全管理
- YTU 2894: G--我要去内蒙古大草原
- Chapter 22 Source Code File REST API Reference (4)
- 内存问题难定位,那是因为你没用ASAN
- 学长告诉我,大厂MySQL都是通过SSH连接的
猜你喜欢
CPU多级缓存与缓存一致性
从产品角度看 L2 应用:为什么说这是一个游乐场?
GPU加速Pinterest推荐模型,参数量增加100倍,用户活跃度提高16%
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
谷歌数据中心发生“电力事故”造成 3 人受伤
Cybersecurity Notes 5 - Digital Signatures
[Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
The impact of development mode on testing
[Go WebSocket] 多房间的聊天室(一)思考篇
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
随机推荐
Gartner再次重申了“数据编织”的重要价值
flask-restplus接口地址404问题
STM32 encapsulation ESP8266 a key configuration function: implementations of AP mode and the STA mode switch, server and the client to create
第5章相似矩阵及二次型(4)
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
如何使用工程仪器设备在线监测管理系统
Get started quickly and conquer three different distributed architecture calling schemes
GPU accelerated Pinterest recommendation model, the number of parameters increased by 100 times, and the user activity increased by 16%
企业如何判断数据治理是否成功?
Centos7环境使用Mysql离线安装包安装Mysql5.7
「业务架构」介绍BPMN第二部分-泳道
ISO9001在讲什么?过程方法和风险思维
L2 applications from a product perspective: why is it a playground?
mysql5.7 installation and deployment - yum installation
是什么影响了MySQL性能?
使用JMeter进行MySQL的压力测试
From the product dimension, why can't we fully trust Layer2?
让软件飞——“X+”技术揭秘
自媒体爆款标题怎么写?手把手教你写热门标题
基于UiAutomator2+PageObject模式开展APP自动化测试实战