Rearrange String k Distance Apart

Given a non-empty string s 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:

Input: s = "aabbcc", k = 3
Output: "abcabc" 
Explanation: The same letters are at least distance 3 from each other.

Example 2:

Input: s = "aaabc", k = 3
Output: "" 
Explanation: It is not possible to rearrange the string.

思路:这题其实是 Reorganize String 的升级版;这里需要跳过K个了。这里用个queue来存储wait的node;

class Solution {
    class Node {
        public char c;
        public int fre;
        public Node(char c, int fre) {
            this.c = c;
            this.fre = fre;
        }
    }
    
    public String rearrangeString(String s, int k) {
        HashMap<Character, Integer> hashmap = new HashMap<>();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            hashmap.put(c, hashmap.getOrDefault(c, 0) + 1);
        }
        
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) ->(b.fre - a.fre));
        for(Character c: hashmap.keySet()) {
            pq.offer(new Node(c, hashmap.get(c)));
        }
        
        StringBuilder sb = new StringBuilder();
        Queue<Node> tempqueue = new LinkedList<>();
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            sb.append(node.c);
            node.fre--;
            tempqueue.offer(node);
            if(tempqueue.size() < k) {
                continue;
            }
            node = tempqueue.poll();
            if(node != null && node.fre > 0) {
                pq.offer(node);
            }
        }
        return sb.length() == s.length() ? sb.toString() : "";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值