Java solution with Clean code


  • 0
    public class Solution {
        public class Node implements Comparable<Node>
        {
            char ch;
            int frequency;
            public Node(char c , int f)
            {
                ch=c;
                frequency=f;
            }
    
            @Override
            public int compareTo(Node o)
            {
                return o.frequency-this.frequency;
            }
        }
        public String rearrangeString(String s, int k) {
            PriorityQueue<Node> pq = new PriorityQueue<>();
            Queue<Node> cooldown = new LinkedList<>();
            StringBuilder rearranged = new StringBuilder();
            int [] alphabets =new int[26];
            for(char ch : s.toCharArray()) { alphabets[ch-'a']++; }
            for(int i=0;i<26;i++)
            {
                if(alphabets[i]==0) continue;
                Node one=new Node((char)(i+'a'),alphabets[i]);
                pq.offer(one);
            }
            while(!pq.isEmpty())
            {
                Node top=pq.poll();
                rearranged.append(top.ch);
                top.frequency--;
                cooldown.offer(top);
                if(cooldown.size()<k){ continue; }
                 Node release =cooldown.poll();
                 if(release.frequency>0){ pq.offer(release); }
            }
            return rearranged.length()<s.length() ? "" : rearranged.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.