当前位置:网站首页>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. 重构字符串(堆)
边栏推荐
- 2022年广东省安全员A证第三批(主要负责人)操作证考试题模拟考试平台操作
- 【DB运营管理/开发解决方案】上海道宁为您提供提高工作便利性的集成开发工具——Orange
- CSAPP Data Lab
- 3342: String manipulation problem solving
- [4G/5G/6G专题基础-154]: 5G无线准入控制RAC(Radio Admission Control)
- 思念家乡的月亮
- Section 4-6 of the first week of the second lesson: Appreciation of medical prognosis cases + homework analysis
- 13.cuBLAS开发指南中文版--cuBLAS中的Level-1函数copy()和dot()
- 软件测试面试题:测试用例与测试脚本?
- 超声图像三维拼接-可视化选择,总体思路
猜你喜欢
【idea 报错】 无效的目标发行版:17 的解决参考
js原型和原型链及原型继承
多线程之ThreadPoolExecutor
alibaba数据同步组件canal的实践整理
Vim and copy and paste from the outside (don't need to install the plugin)
测试3年,开口就要25k?面试完最多给15k...
JVM类加载机制
DOM-DOM树,一个DOM树有三种类型的节点
Js prototype and prototype chain and prototype inheritance
【Unity入门计划】Unity2D动画(1)-动画系统的组成及功能的使用
随机推荐
Deep Learning - Second Time
软件测试面试题:什么是Negative测试?
数据的存储(下)——浮点型在内存中的存储
【PHP】入门知识
HPSO and multi-core LSSVM based network intrusion detection
软件测试面试题:谈谈你对 cmm 和 is9000 的认识?
YTU 2411: 谁去参加竞赛?【简单循环】
想进阿里?先来搞懂一下分布式事务
Oops novice template Framework project guide
CC0 与商业 IP:哪种模式更适合 NFT?
JS-DOM元素对象
Future Trends in Vulnerability Management Programs
软件测试面试题:在频繁的版本发布中,如何回归测试?
ES6进阶 字符串处理新特性
0 in the figure, etc. LeetCode565. Array nesting
Ninjutsu_v3_08_2020-安全渗透系统安装
一次简单的 JVM 调优,拿去写到简历里
数论基础-整除(编程例题)
ifconfig与ip命令的比较
备战“金九银十”,软件测试功能 / 数据库 /linux/ 接口 / 自动化 / 测试开发面试真题解析