【leetcode】451. Sort Characters By Frequency
2024-09-07 15:03:19
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them.
考察了map的创建,map转存到vector,函数参数传递进去自定义排序(关系仿函数)这题还是比较需要基本功的。
class Solution {
public:
// 仿函数
typedef pair<char,int> PAIR;
struct CmpByValue{
bool operator()(const PAIR& lhs,const PAIR& rhs){
return lhs.second>=rhs.second;//
}
};
string frequencySort(string s) {
//按照频率统计字符串 第一件事情就是要提取出字符 计算频率
//哈希表进行排序?
// 处理步骤 先用map村数值 然后转存到vector 指定仿函数修改排序规则
map<char,int> dp;
for(char ss:s){
if(dp.find(ss)==dp.end()){
dp[ss]=1;
}
else{
dp[ss]++;
}
}
// 将map元素转存到vector中
vector<PAIR> dp2(dp.begin(),dp.end());
// 对vector排序
sort(dp2.begin(),dp2.end(),CmpByValue());
//根据排序后的元素拼接新的字符串
string res="";
for(auto dd:dp2){
string tmp(dd.second,dd.first);
res+=tmp;
}
return res;
}
};
为了避免map中key键值重复的问题 利用优先队列(默认大顶堆)重建以出现次数为key的优先队列,减少时间复杂度。
class Solution {
public: string frequencySort(string s) {
//按照频率统计字符串 第一件事情就是要提取出字符 计算频率
//哈希表进行排序?
// 处理步骤 先用map村数值 然后转存到vector 指定仿函数修改排序规则
map<char,int> dp;
for(char ss:s){
dp[ss]++; }
//利用优先队列 大顶堆直接做
priority_queue<pair<int,char>> q;//这样避免了key不能重复的问题
string res="";
for(auto dd:dp){
q.push({dd.second,dd.first});
}
while(!q.empty()){
auto c=q.top();
string tmp(c.first,c.second);
res+=tmp;
q.pop();
} return res; }
};
最新文章
- 基于 Eclipse 的 MapReduce 开发环境搭建
- 计算机启动boot
- 解决Chrome谷歌浏览器不支持CSS设置小于12px的文字
- Android四大组件——Activity
- Java ftp 上传文件和下载文件
- 阿里云服务器 yii2执行composer提示报错
- php 配置xdebug
- python之类和对象
- Java程序猿怎样高速理解Kubernetes
- Easyui datagrid 特殊处理,记录笔记
- Nuxt学习笔记
- Appscan_web安全测试工具 (含修改启动浏览器的方法)
- objective C, parse json时注意事项
- 《Effective C++》item25:考虑写出一个不抛异常的swap函数
- 装饰 Markdown
- 如何在 CentOS 7 中安装、配置和安全加固 FTP 服务
- HBase相关概念
- Leetcode 12
- SecureCRT中 secureCRT使用VIM时对语法高亮
- Mac os x 下配置Intellij IDEA + Tomcat 出现权限问题的解决办法
热门文章
- 第01课 OpenGL窗口(1)
- springcloud3(六) 服务降级限流熔断组件Resilience4j
- PE节表详细分析
- 攻防世界 WEB 高手进阶区 XCTF 4th-CyberEarth ics-06 Writeup
- MySQL基础学习——SQL对数据库进行操作、对数据库的表进行操作
- IDEA中三种注释方式的快捷键
- Django笔记&教程 2-3 视图(view)函数介绍
- Arduino uno r3 使用 ESP8266 UART-WiFi 透传模块
- [loj2462]完美的集合
- [nowcoder5666B]Infinite Tree