Given a non-empty string str 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:
str = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
 Analysis:
Solution 1:
The greedy algorithm is that in each step, select the char with highest remaining count if possible (if it is not in the waiting queue).  Everytime, we add the char X with the largest remaining count, after that we should put it back to the queue (named readyQ) to find out the next largest char. HOWEVER, do not forget the constraint of K apart. So we should make char X waiting for K-1 arounds of fetching and then put it back to queue. We use another queue (named waitingQ) to store the waiting chars. Whenever, the size of this queue equals to K, the head char is ready to go back to readyQ.
 
Solution 2:
Based on solution 1, we do not use PriorityQueue, instead, we just use array with 26 elements to store chars' count and its next available position. Every round, we iterate through the arrays and find out the available char with max count.
 
NOTE: theoretically, the complexity of solution 1 using PriorityQueue is O(nlog(26)), while the complexity of solution 2 is O(n*26) which is larger than solution 1. HOWEVER, in real implementation, because solution 1 involves creating more complex data structures and sorting them, soluiont 1 is much slower than solution 2.
 
Solution 1: Greedy Using Heap, Time Complexity: O(Nlog(26))
What I learn: Map.Entry can be a very good Wrapper Class, you can directly use it to implement heap without writing a wrapper class yourself
 public class Solution {
public String rearrangeString(String str, int k) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
Queue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(1, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> entry1, Map.Entry<Character, Integer> entry2) {
return entry2.getValue()-entry1.getValue();
} });
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
maxHeap.offer(entry);
}
Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>();
StringBuilder res = new StringBuilder(); while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> entry = maxHeap.poll();
res.append(entry.getKey());
entry.setValue(entry.getValue()-1);
waitQueue.offer(entry);
if (waitQueue.size() >= k) {
Map.Entry<Character, Integer> unfreezeEntry = waitQueue.poll();
if (unfreezeEntry.getValue() > 0) maxHeap.offer(unfreezeEntry);
}
}
return res.length()==str.length()? res.toString() : "";
}
}

Solution2: Greedy Using Array, Time Complexity: O(N*26)

 public class Solution {
public String rearrangeString(String str, int k) {
int[] count = new int[26];
int[] nextValid = new int[26];
for (int i=0; i<str.length(); i++) {
count[str.charAt(i)-'a']++;
}
StringBuilder res = new StringBuilder();
for (int index=0; index<str.length(); index++) {
int nextCandidate = findNextValid(count, nextValid, index);
if (nextCandidate == -1) return "";
else {
res.append((char)('a' + nextCandidate));
count[nextCandidate]--;
nextValid[nextCandidate] += k;
}
}
return res.toString();
} public int findNextValid(int[] count, int[] nextValid, int index) {
int nextCandidate = -1;
int max = 0;
for (int i=0; i<count.length; i++) {
if (count[i]>max && index>=nextValid[i]) {
max = count[i];
nextCandidate = i;
}
}
return nextCandidate;
}
}

Leetcode: Rearrange String k Distance Apart的更多相关文章

  1. [LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

    Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...

  2. 358. Rearrange String k Distance Apart

    /* * 358. Rearrange String k Distance Apart * 2016-7-14 by Mingyang */ public String rearrangeString ...

  3. LC 358. Rearrange String k Distance Apart

    Given a non-empty string s and an integer k, rearrange the string such that the same characters are ...

  4. LeetCode 358. Rearrange String k Distance Apart

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

  5. [LeetCode] 358. Rearrange String k Distance Apart 按距离k间隔重排字符串

    Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...

  6. 【LeetCode】358. Rearrange String k Distance Apart 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/rearrang ...

  7. [Swift]LeetCode358. 按距离为k隔离重排字符串 $ Rearrange String k Distance Apart

    Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...

  8. [LeetCode] Reorganize String 重构字符串

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  9. [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

随机推荐

  1. Python爬虫学习(2): httplib

    httplib模块实现了HTTP和HTTPS的客户端部分,但是一般不直接使用,经常通过urllib来进行HTTP,HTTPS的相关操作. 如果需要查看其源代码可以通过查找命令定位: find / -n ...

  2. 点 击 直 接加我QQ的功能

    <a target="_blank" href="tencent://message/?uin=2814920598&Site=&Menu=yes& ...

  3. [BZOJ4027][HEOI2015] 兔子与樱花

    Description 很久很久之前,森林里住着一群兔子.有一天,兔子们突然决定要去看樱花.兔子们所在森林里的樱花树很特殊.樱花树由n个树枝分叉点组成,编号从0到n-1,这n个分叉点由n-1个树枝连接 ...

  4. 【Redis】简介与安装

    Linux 安装 [root@redis ~]# wget http://download.redis.io/releases/redis-2.8.19.tar.gz 解压缩redis[root@ha ...

  5. 【资料下载区】【iCore3相关代码、资料下载地址】更新日期2017/1/5

    [iCore3 ARM代码下载地址][全部]DEMO1.0测试程序发布例程一:ARM驱动三色LED例程二:读取arm按键状态例程三:EXTI中断输入实验——读取ARM按键状态例程四:USART通信实验 ...

  6. 【5集iCore3_ADP演示视频】5-2 iCore3应用开发平台上电及注意事项

    iCore3双核心应用开发平台基于iCore3双核心板,包含ARM.FPGA.7寸液晶屏.双通道数字示波器.任意波发生器.电压表等模块,是一款专为电子爱好者设计的综合性电子学习系统. [视频简介]本视 ...

  7. php获得http头部信息的方法

    $url = 'http://www.baidu.com'; $fp = fopen($url, 'r'); $meta_data = stream_get_meta_data($fp); var_d ...

  8. 加速下载gradle

    http://www.jianshu.com/p/e887203e30f6 另外idea runconfiguration里边 gradle project要选项目根目录,而不是build脚本.

  9. 2016.10.14,英语,《American Accent Training》

    这本书是讲述美语发音训练的.已经看了一段时间了,决定向周叶学习,记录读书笔记.计划每天花半个小时,学习3节左右的音频(按照CD TRACK),并完成训练. CD1 Track1 What is Acc ...

  10. 微博mid和id转换

    mid为62进制编码,id为常见的10进制编码. id从低位到高位,7个数字为一组,转换为62进制,并顺序合并,即转换为mid. mid从地位到高位,4个字母为一组,转换为10进制,并右移7位,计算和 ...