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. JavaScript预解析1

    var 不一定是用来定义局部变量的 jscript的全局变量和局部变量的分界是这样的:                  过程体(包括方法function,对象Object o ={})外的所有变量不 ...

  2. linux 查找文件或者内容常用命令

    whereis <程序名称> find [路径] <表达式> locate <文件名称> 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符 ...

  3. hdu4135 容斥定理

    Co-prime Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Su ...

  4. JBD日志的定位、分析和恢复

    在上一篇中,我们介绍了Ext3文件系统的日志可以看做一个文件,由JBD进行管理.自然而然引出如下这些问题: 1)如何定位ext3日志文件和查看日志文件的裸数据? 2)ext3日志文件数据在物理上是如何 ...

  5. 洛谷 P1373 小a和uim之大逃离 Label:dp 不会

    题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北部天边急涌过来,还伴着一道道闪电,一阵阵雷声.刹那间,狂风大作,乌云布满了天空,紧接着豆大的雨点从天空中打落下来,只见前方出现了一个 ...

  6. POJ 1637 Sightseeing tour(混合图的欧拉回路)

    题目链接 建个图,套个模板. #include <cstdio> #include <cstring> #include <iostream> #include & ...

  7. .net获取DataTable里面的值(asp.net遍历获取datatable的值)

    方法一:for (int i =0; i < dtb_xx.Rows.Count; i++ ){response.write dtb_xx.Rows[i]["szxxxx1" ...

  8. ZeroMQ接口函数之 :zmq_msg_size - 以字节为单位返回消息内容的大小

    ZeroMQ 官方地址 :http://api.zeromq.org/4-2:zmq_msg_size zmq_msg_size(3)  ØMQ Manual - ØMQ/3.2.5 Name zmq ...

  9. *cf.4 贪心

    D. Kostya the Sculptor time limit per test 3 seconds memory limit per test 256 megabytes input stand ...

  10. BS中的 data:image/png;base64

    举个图片的例子: 网页中一张图片可以这样显示: <img src="http://mail.163.com/images/x.png" /> 也可以这样显示: < ...