博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Rearrange String k Distance Apart
阅读量:7123 次
发布时间:2019-06-28

本文共 3431 字,大约阅读时间需要 11 分钟。

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 = 3Result: "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 = 2Answer: "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
1 public class Solution { 2     public String rearrangeString(String str, int k) { 3         Map
map = new HashMap
(); 4 for (int i=0; i
> maxHeap = new PriorityQueue<>(1, new Comparator
>() { 9 public int compare(Map.Entry
entry1, Map.Entry
entry2) {10 return entry2.getValue()-entry1.getValue();11 }12 13 });14 for (Map.Entry
entry : map.entrySet()) {15 maxHeap.offer(entry);16 }17 Queue
> waitQueue = new LinkedList<>();18 StringBuilder res = new StringBuilder();19 20 while (!maxHeap.isEmpty()) {21 Map.Entry
entry = maxHeap.poll();22 res.append(entry.getKey());23 entry.setValue(entry.getValue()-1);24 waitQueue.offer(entry);25 if (waitQueue.size() >= k) {26 Map.Entry
unfreezeEntry = waitQueue.poll();27 if (unfreezeEntry.getValue() > 0) maxHeap.offer(unfreezeEntry);28 }29 }30 return res.length()==str.length()? res.toString() : "";31 }32 }

 

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

1 public class Solution { 2     public String rearrangeString(String str, int k) { 3         int[] count = new int[26]; 4         int[] nextValid = new int[26]; 5         for (int i=0; i
max && index>=nextValid[i]) {26 max = count[i];27 nextCandidate = i;28 }29 }30 return nextCandidate;31 }32 }

 

转载地址:http://fvael.baihongyu.com/

你可能感兴趣的文章
流媒体技术
查看>>
100亿数据找出最大的1000个数字(top K问题)
查看>>
常见JAVA问题定位1
查看>>
S5PV210-uboot源码分析-uboot命令体系
查看>>
JDK8-废弃永久代(PermGen)迎来元空间(Metaspace)
查看>>
开源web 架构
查看>>
sscanf() 函数
查看>>
poj - 1061 青蛙的约会【扩展欧几里】
查看>>
通过调用firefox无法使用鼠标事件,解决办法
查看>>
1.站长工具网站地址
查看>>
centos redis 主从配置+哨兵模式
查看>>
typedef struct和struct 的区别 用途
查看>>
八皇后问题---详解---参考<<紫书>>
查看>>
P2325 [SCOI2005]王室联邦
查看>>
Request
查看>>
错题解析
查看>>
C++命名空间
查看>>
C语言文件操作
查看>>
session(会话)研究(一)基础
查看>>
DNS解析全过程分析
查看>>