• Rearrange String k Distance Apart


    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。
    同 G面经prepare: Reorder String to make duplicates not consecutive:字符串重新排列,让里面不能有相同字母在一起。比如aaabbb非法的,要让它变成ababab。给一种即可
    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;
        }
    }
    

      

  • 相关阅读:
    Nokia Qt SDK开发环境使用
    iPad不久将能使用Android系统
    原生IDE新军:JRuby阵营的RedCar,JavaScript阵营的Cloud9(自己写个IDE出来一定很复杂吧)
    手机产品的信息架构
    百万开发者拥戴!七大.NET著名开源项目
    Prism 4.0发布最终版,支持Windows Phone 7
    Qt Symbian 开发环境安装
    Qt 4.7.1 和 Mobility 1.1.0 已发布
    WSI闭关,这对WS*意味着什么?(个人觉得Web Services是个好东西)
    ERROR: unknown virtual device name解决方法
  • 原文地址:https://www.cnblogs.com/apanda009/p/7801229.html
Copyright © 2020-2023  润新知