原题链接在这里:https://leetcode.com/problems/rearrange-string-k-distance-apart/description/

题目:

Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.

All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".

Example 1:

s = "aabbcc", k = 3Result: "abcabc"The same letters are at least distance 3 from each other.

Example 2:

s = "aaabc", k = 3 Answer: ""It is not possible to rearrange the string.

Example 3:

s = "aaadbbcc", k = 2Answer: "abacabcd"Another possible answer is: "abcabcda"The same letters are at least distance 2 from each other.

题解:

Greedy问题. 感觉上是应该先排剩余frequency 最多的Character.

用maxHeap来维护剩余的Character, 根据剩余的count.

那么如何保持断开的距离大于k呢, 用queue来存放已经加过的Character, 只有当queue的size等于k时, 才允许把头上的Character放回到maxHeap中.

Time Complexity: O(nlogn). n = s.length(). 都加入进maxHeap用时O(nlogn).

Space: O(n).

AC Java:

 1 class Solution {
 2     public String rearrangeString(String s, int k) {
 3         if(s == null || s.length() == 0){
 4             return s;
 5         }
 6
 7         HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
 8         for(int i = 0; i<s.length(); i++){
 9             hm.put(s.charAt(i), hm.getOrDefault(s.charAt(i), 0)+1);
10         }
11
12         PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>(
13             (a, b) -> b.getValue() - a.getValue()
14         );
15         maxHeap.addAll(hm.entrySet());
16
17         LinkedList<Map.Entry<Character, Integer>> que = new LinkedList<Map.Entry<Character, Integer>>();
18         StringBuilder sb = new StringBuilder();
19         while(!maxHeap.isEmpty()){
20             Map.Entry<Character, Integer> cur = maxHeap.poll();
21             sb.append(cur.getKey());
22             cur.setValue(cur.getValue()-1);
23             que.add(cur);
24
25             if(que.size() < k){
26                 continue;
27             }
28
29             Map.Entry<Character, Integer> head = que.poll();
30             if(head.getValue() > 0){
31                 maxHeap.add(head);
32             }
33         }
34         return sb.length() == s.length() ? sb.toString() : "";
35     }
36 }

时间上可以优化.

利用两个int array, count计数剩余frequency, validPo代表这个字符能出现的最早位置.

找到最大frequency的合法字符, 更新其对应的frequency 和 再次出现的位置.

Time Complexity: O(s.length()). findMaxValidCount走了遍长度为i26的count array.

Space: O(s.length()). StringBuilder size.

AC Java:

 1 class Solution {
 2     public String rearrangeString(String s, int k) {
 3         if(s == null || s.length() == 0){
 4             return s;
 5         }
 6
 7         int [] count = new int[26];
 8         int [] validPo = new int[26];
 9         for(int i = 0; i<s.length(); i++){
10             count[s.charAt(i)-'a']++;
11         }
12
13         StringBuilder sb = new StringBuilder();
14         for(int i = 0; i<s.length(); i++){
15             int po = findMaxValidCount(count, validPo, i);
16             if(po == -1){
17                 return "";
18             }
19
20             sb.append((char)('a'+po));
21             count[po]--;
22             validPo[po] = i+k;
23         }
24         return sb.toString();
25     }
26
27     private int findMaxValidCount(int [] count, int [] validPo, int ind){
28         int po = -1;
29         int max = Integer.MIN_VALUE;
30         for(int i = 0; i<count.length; i++){
31             if(count[i]>0 && count[i]>max && ind>=validPo[i]){
32                 max = count[i];
33                 po = i;
34             }
35         }
36
37         return po;
38     }
39 }

类似Task Scheduler.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7743174.html

LeetCode Rearrange String k Distance Apart相关推荐

  1. 优先队列之Leetcode 23合并K个有序链表

    优先队列要点复习 这在之前专门写过一篇文章讲优先队列的使用方法: 优先队列的优先级设置法 对于优先队列,我们首先需要知道,它的底层是堆,或者说优先队列是堆的一种别称.堆自然就分成了两个方向: 大顶堆 ...

  2. leetcode 1400. 构造 K 个回文字符串

    leetcode 1400. 构造 K 个回文字符串 文章目录 leetcode 1400. 构造 K 个回文字符串 一.题目 1.题目描述 2.基础框架 3.解题思路 一.题目 原题链接:1400. ...

  3. Leetcode 347. 前 K 个高频元素

    Leetcode 347. 前 K 个高频元素 1.问题分析 2.问题解决 3.总结 1.问题分析 题目链接:https://leetcode-cn.com/problems/top-k-freque ...

  4. leetcode 373. Find K Pairs with Smallest Sums | 373. 查找和最小的K对数字(小根堆)

    题目 https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ 题解 本来以为是个双指针+贪心,但是后来发现如果用双指针的话,指针并 ...

  5. [分治] leetcode 23 合并K个升序链表

    [分治] leetcode 23 合并K个升序链表 1.题目 题目链接 给你一个链表数组,每个链表都已经按升序排列. 请你将所有链表合并到一个升序链表中,返回合并后的链表. 示例1: 输入:lists ...

  6. 【细节实现题】LeetCode 8. String to Integer (atoi)

    LeetCode 8. String to Integer (atoi) Solution1:我的答案 参考链接:http://www.cnblogs.com/grandyang/p/4125537. ...

  7. LeetCode——347. 前 K 个高频元素【最小堆实现】

    LeetCode--347. 前 K 个高频元素[最小堆实现] 给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素.你可以按 任意顺序 返回答案. 示例1: 输入: n ...

  8. 【LeetCode】849. Maximize Distance to Closest Person

    [LeetCode]849. Maximize Distance to Closest Person 849. Maximize Distance to Closest Person Easy In ...

  9. 【LeetCode】849. Maximize Distance to Closest Person 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

最新文章

  1. Vijos P1131 最小公倍数和最大公约数问题【暴力】
  2. 佳能单反相机二次开发包介绍_家用单反相机什么牌子好
  3. Jenkins FTP 上传
  4. redis(9)--数据库
  5. 外包以小时计算金额的费用_2020年初级会计各大税种的计算公式,请收藏!
  6. BIFR的完整形式是什么?
  7. C# ADO.NET
  8. php图型分析插件,IMAGE缩略图插件
  9. Linux 安装配置JDK 、 MySQL 、nginx
  10. linux date -s_Linux炫技:左手密码生成器,解放右手生产力
  11. K8S实战之部署java应用
  12. php报503怎么排查,php监控日志500、503错误并发送邮件提示的代码
  13. hh-suite使用教程
  14. mapgis k9将wp、wl、wt转shp属性字段名乱码
  15. samba4的负载均衡群集
  16. win10关机后cpu风扇还在转_电脑关机后CPU风扇还在转的原因和解决办法
  17. 台式计算机关闭屏幕快捷键,关闭电脑屏幕的快捷键
  18. android手机微信输入蓝色字体,微信彩色昵称怎么制作?微信个性蓝色昵称设置图文教程与方法...
  19. 动手| 一个人脸识别的K8s部署实践
  20. linux虚拟机mtr不出去,如何使用MTR诊断网络问题

热门文章

  1. 详细解读八大无线网络安全技术利弊
  2. 中国古代道家思想与网页重构的思考
  3. delphi2010中FastReport的安装方法
  4. 瑞星对Windows7捆绑杀毒软件等消息的回应
  5. 参观云栖小镇体会_云栖小镇感受
  6. 浅析托管与非托管C++代码(转)
  7. matlab std函数_MATLAB金融工具箱:11:根据基准优化投资组合
  8. mtl库在GCC编译器下的使用
  9. ArcGIS 栅格函数在线调用详解
  10. 微信小程序开发资料汇总