当前位置:网站首页>leetcode:451. Sort by character frequency
leetcode:451. Sort by character frequency
2022-04-22 16:55:00 【Oceanstar's study notes】
Title source
Title Description

title
Priority queue
- First use unordered_map Count the frequency of each letter ,key by char,value by cnt
- And then use it priority_queue The characteristics of finite queues
- A finite queue is a large root heap by default , The big number comes first
- pair Sort rule : First, according to first(cnt) Sort ; If first equal , So according to second(char) Sort
- And then from priority_queue Take out the data , Press into the result string
class Solution {
public:
string frequencySort(string s) {
std::unordered_map<char, int> m;
for(auto ch : s){
++m[ch];
}
std::priority_queue<std::pair<int, char>> q;
for(auto it : m){
q.push({
it.second, it.first});
}
std::string ans;
while (!q.empty()){
auto t = q.top(); q.pop();
ans.append(t.first, t.second);
}
return ans;
}
};

rewrite sort Of cmp
We can also use STL Self contained sort To do it , The key is to rewrite comparator, Due to the need to use external variables , Remember to put... In brackets &, Then we will return with high frequency , Be sure to deal with the same frequency , Otherwise, two characters with equal frequency may appear interspersed in the result res in , It's not right . See code below :
class Solution {
public:
string frequencySort(string s) {
std::unordered_map<char, int> m;
for(auto ch : s){
++m[ch];
}
std::sort(s.begin(), s.end(), [&](char &a, char &b){
return m[a] > m[b] || (m[a] == m[b] && a < b); // If the frequency is the same , Put the small one in the front
});
return s;
}
};

Count sorting
We can also avoid the priority queue , Instead, create an array of strings , because A character cannot appear more than s The length of , So we put each character into the corresponding position in the array according to its occurrence times , So in the end, we just Go back and forth Array all positions , Add the string of non empty position to the result res Then you can , See code below :
class Solution {
public:
string frequencySort(string s) {
std::unordered_map<char, int> m;
for(auto ch : s){
++m[ch];
}
std::string ans;
std::vector<std::string> vec(s.size() + 1);
for(auto & a : m){
vec[a.second].append(a.second, a.first);
}
for (int i = s.size(); i > -1; --i) {
if(!vec[i].empty()){
ans.append(vec[i]);
}
}
return ans;
}
};

版权声明
本文为[Oceanstar's study notes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221651051270.html
边栏推荐
- 力扣解法汇总396-旋转函数
- Facing the global market, platefarm today logs in to four major global platforms such as Huobi
- Golang的JWT权限校验解析
- 《KNN与K-means从入门到实战》
- [interview ordinary people vs Expert Series] please talk about the network quadruple
- Agile practice | agile indicators to improve group predictability
- ifconfig、route、ip route、ip addr、 ip link 用法
- RTP packaging and unpacking of webrtc
- SDN学习之Opendaylight浅析(二)
- Domestic mobile phone brands have found that they are nothing without the support of domestic consumers
猜你喜欢

Domestic mobile phone brands have found that they are nothing without the support of domestic consumers
![[corner detection]](/img/37/fbcf7f4bedfdfb531fcbe1475f2d92.png)
[corner detection]

Blue Bridge Cup practice 014

Summary of process and principle of solution to concurrency problem (form repeated submission problem)

RT thread studio workspace encoding is set to UTF-8

4亿女性刚需,各路资本杀伐:藏在卫生巾里的1000亿生意

RT-Thread Studio 对代码进行格式化

Cvpr2019 domain adaptation / semantic segmentation: adapting structural information across domains for boosting SEMA
![[appium] simple transplantation of unittest framework of Youdao cloud app and design of driver file](/img/d0/1ad6f79c9ae9f9e2d50495c2f37efb.png)
[appium] simple transplantation of unittest framework of Youdao cloud app and design of driver file

GlboalMapper20 如何一次性把上百个经纬度投影的影像转为国家2000或者其他投影的影像
随机推荐
VSCode 最全实用插件(VIP典藏版)
基于深度模型的日志序列异常检测
swagger Authorization测试
Blue Bridge Cup practice 020
Blue Bridge Cup practice 019
《KNN与K-means从入门到实战》
Facing the global market, platefarm today logs in to four major global platforms such as Huobi
bisect——对列表插入新数据仍然保持有序
Force deduction solution summary 396 rotation function
What is the advantage of asemi low voltage drop Schottky diode over ordinary Schottky diode?
ASP.NET Core实现JWT授权与认证(2.实战篇)
Blue Bridge Cup practice 014
STM32的一种串口数据接受方式
[filtering and convolution (II)]
LeetCode刷题计划——单调数列
C determines whether the database return record is a null DbNull class DbNull Value. Equals(row[fieldName]
敬語 謙譲
对数器的概念和使用
Scrapy框架进阶学习
【ES6】扩展运算符、symbol、迭代器