358. Rearrange String k Distance Apart

题目链接:https://leetcode.com/problems...

greedy的思想,这题要让相同字母的character距离至少为k,那么首先要统计字母出现的次数,然后根据出现的次数来对字母排位置。出现次数最多的肯定要先往前面的位置排,这样才能尽可能的满足题目的要求。建一个heap,存char和剩余次数,每次从heap里面取k个不同的字母出来排,把字母放入一个大小为k的q里面等待,直到距离到k的时候再释放。
参考:
https://discuss.leetcode.com/...

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();
    }
}

lulouch13
13 声望6 粉丝