358. Rearrange String k Distance Apart

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值