358. Rearrange String k Distance Apart

358. Rearrange String k Distance Apart

題目連接:https://leetcode.com/problems...java

greedy的思想,這題要讓相同字母的character距離至少爲k,那麼首先要統計字母出現的次數,而後根據出現的次數來對字母排位置。出現次數最多的確定要先往前面的位置排,這樣才能儘量的知足題目的要求。建一個heap,存char和剩餘次數,每次從heap裏面取k個不一樣的字母出來排,把字母放入一個大小爲k的q裏面等待,直到距離到k的時候再釋放。
參考:
https://discuss.leetcode.com/...app

public class Solution {
    public String rearrangeString(String s, int k) {
        int n = s.length();
        // count the characters
        int[] map = new int[26];
        for(int i = 0; i < n; i++) map[s.charAt(i) - 'a']++;
        // [0]: char, [1]: frequency
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        // wait queue
        Queue<int[]> wait = new LinkedList();
        // add all characters
        for(int i = 0; i < map.length; i++) {
            if(map[i] != 0) heap.offer(new int[] {i, map[i]});
        }
        
        StringBuilder res = new StringBuilder();
        // loop invariant: all char in heap is k away from last time
        while(!heap.isEmpty()) {
            int[] cur = heap.poll();
            res.append((char) ('a' + cur[0]));
            cur[1] = cur[1] - 1;
            // add to wait queue
            wait.add(cur);
            // if already k away from wait queue, add to heap
            if(wait.size() >= k) {
                int[] release = wait.poll();
                if(release[1] > 0) heap.offer(release);
            }
        }
        // invalid
        if(res.length() != n) return "";
        return res.toString();
    }
}
相關文章
相關標籤/搜索