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; }
};

  

最新文章

  1. 基于 Eclipse 的 MapReduce 开发环境搭建
  2. 计算机启动boot
  3. 解决Chrome谷歌浏览器不支持CSS设置小于12px的文字
  4. Android四大组件——Activity
  5. Java ftp 上传文件和下载文件
  6. 阿里云服务器 yii2执行composer提示报错
  7. php 配置xdebug
  8. python之类和对象
  9. Java程序猿怎样高速理解Kubernetes
  10. Easyui datagrid 特殊处理,记录笔记
  11. Nuxt学习笔记
  12. Appscan_web安全测试工具 (含修改启动浏览器的方法)
  13. objective C, parse json时注意事项
  14. 《Effective C++》item25:考虑写出一个不抛异常的swap函数
  15. 装饰 Markdown
  16. 如何在 CentOS 7 中安装、配置和安全加固 FTP 服务
  17. HBase相关概念
  18. Leetcode 12
  19. SecureCRT中 secureCRT使用VIM时对语法高亮
  20. Mac os x 下配置Intellij IDEA + Tomcat 出现权限问题的解决办法

热门文章

  1. 第01课 OpenGL窗口(1)
  2. springcloud3(六) 服务降级限流熔断组件Resilience4j
  3. PE节表详细分析
  4. 攻防世界 WEB 高手进阶区 XCTF 4th-CyberEarth ics-06 Writeup
  5. MySQL基础学习——SQL对数据库进行操作、对数据库的表进行操作
  6. IDEA中三种注释方式的快捷键
  7. Django笔记&教程 2-3 视图(view)函数介绍
  8. Arduino uno r3 使用 ESP8266 UART-WiFi 透传模块
  9. [loj2462]完美的集合
  10. [nowcoder5666B]Infinite Tree