当前位置:网站首页>leetcode:358. K 距离间隔重排字符串
leetcode:358. K 距离间隔重排字符串
2022-08-11 02:37:00 【OceanStar的学习笔记】
题目来源
题目描述

class Solution {
public:
string rearrangeString(string str, int k) {
}
};
题目解析
思路:
- 准备:
- 先统计所有字符出现的次数,存入一个map中(key = char, value = count)
- 然后使用map按照重复次数从大到小构建一个大根堆
- 创建一个string ans对象用来表示结果
- 创建一个queue来同步已经加入到ans中的字符
- 循环遍历大根堆的字符
- 先插入的是数字最多的字符,插入之后将这个字符的数量-1,然后把这个字符移到queue中(因为下一次不能插入它了,必须等到长度到达k之后才能插入它)
- 然后判断queue中的元素是否为k,如果是的话,说明队头的元素可以再次尝试去插入了,因此将它放入到大根堆里面
- 最后,当大根堆为空时:
- 如果ans.size == ori.size说明重构完成,返回ans
- 如果ans.size != ori.size,说明还有些字符挂在queue中,重构失败,返回""
class Solution {
public:
string rearrangeString(string str, int k) {
if(k == 0){
return str;
}
int N = str.size();
std::string ans;
std::unordered_map<char, int> m;
// 遍历字符,统计字符的出现次数
for(auto c : str){
m[c]++;
}
// 装入大顶堆,按照字符重复次数作为比较
std::priority_queue<pair<char, int>, std::vector<pair<char, int>>,
cmp> maxHeap(m.begin(), m.end());
std::queue<pair<char, int>> queue;
while (!maxHeap.empty()){
auto curr = maxHeap.top(); maxHeap.pop();// 从大顶堆取出重复次数最多的字符
ans += curr.first;
curr.second--;// 用掉一个字符,次数减一
queue.push(curr);// 放入到queue中,因为k距离后还要用
if(queue.size() == k){
// queue的大小到达了k,也就是说我们已经越过了k个单位,在结果中应该要出现相同的字母了
auto f = queue.front(); queue.pop();
if(f.second > 0){
// 该字符的重复次数大于 0,则添加入大顶堆中,要是0那还加它干嘛
maxHeap.push(f);
}
}
}
return ans.size() == str.size() ? ans : "";
}
};
类似题目
- leetcode:358. K 距离间隔重排字符串
- leetcode:621. Task Scheduler
- leetcode:767. 重构字符串(堆)
边栏推荐
猜你喜欢

JVM类加载机制

OptiFDTD应用:用于光纤入波导耦合的硅纳米锥仿真

【C 数据存储详解】(1)——深度剖析整形数据在内存中的存储

项目构建工具-Gradle入门

Alibaba 最新神作!耗时 182 天肝出来 1015 页分布式全栈手册太香了
![[oops-framework] Template project [oops-game-kit] Introduction](/img/09/29faf7626b0bc66e4d016a15e80b8b.png)
[oops-framework] Template project [oops-game-kit] Introduction

alibaba数据同步组件canal的实践整理

从键入网址到网页显示的详细过程

【oops-framework】模板项目【oops-game-kit】使用简介

WeChat public account background management
随机推荐
DOM-DOM树,一个DOM树有三种类型的节点
JS-DOM元素对象
LitePal操作数据库
A surviving spouse of the opposite sex within large turn paragraph, what for
《人生若如初见》命运多舛,人物饱满,朱亚文角色反差太惊喜
八.数据的存储
①In-depth analysis of CAS SSO single sign-on framework source code
Mysq_Note4
想进阿里?先来搞懂一下分布式事务
ESP32的环境配置(arduino arduino2.0 VScode platform哪个好用?)
YTU 2411: 谁去参加竞赛?【简单循环】
ES6 advanced string processing new features
shell脚本入门
Detailed explanation of new features of ES advanced function syntax
BUU刷题记录
shell [stdin/stdout/stderr][重定向]
14.cuBLAS开发指南中文版--cuBLAS中的Level-1函数nrm2()和rot()
Mysql_Note6
SIT221 Data Structures and Algorithms课程辅导
一次简单的 JVM 调优,拿去写到简历里