当前位置:网站首页>力扣练习——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;
}
边栏推荐
- Get started quickly and conquer three different distributed architecture calling schemes
- 使用cpolar远程连接群晖NAS(升级固定链接2)
- 是什么影响了MySQL性能?
- Nocalhost - 让云原生时代的开发更高效
- Mount [shell][mount -o loop]
- Cybersecurity Notes 5 - Digital Signatures
- L2 applications from a product perspective: why is it a playground?
- OneFlow源码解析:算子指令在虚拟机中的执行
- 3款不同类型的自媒体免费工具,有效提高创作、运营效率
- Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
猜你喜欢
随机推荐
快速上手,征服三种不同分布式架构调用方案
杭电多校-Loop-(不确定性贪心+线段树)
OSSCore 开源解决方案介绍
How can an organization judge the success of data governance?
用proteus直接仿真stm32-可以完全丢弃编程器
Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
The brave rice rice, does not fear the brush list of 】 list has a ring
使用哈工大LTP测试分词并且增加自定义字典
4 of huawei offer levels, incredibly side is easing the bit in the interview ali?
基于UiAutomator2+PageObject模式开展APP自动化测试实战
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists
Codeforces 814 C. An impassioned circulation of affection (dp)
组合模式:Swift 实现
GPU加速Pinterest推荐模型,参数量增加100倍,用户活跃度提高16%
ENVI 5.3软件安装包和安装教程
ISO9001在讲什么?过程方法和风险思维
谷歌数据中心发生“电力事故”造成 3 人受伤
STM32封装ESP8266一键配置函数:实现实现AP模式和STA模式切换、服务器与客户端创建
OneFlow源码解析:算子指令在虚拟机中的执行
实现内网穿透的最佳解决方案(无实名认证,完全免费)