Reorganize String

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result.  If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:


Solution:

class Solution {
    static class Node implements Comparable<Node>{
        char c;
        int freq;
        
        public Node(char c, int freq) {
            this.c = c;
            this.freq = freq;
        }
        
        @Override
        public int compareTo(Node b) {
            int com = Integer.compare(b.freq, this.freq);
            if (com == 0) {
                return this.c - b.c;
            } else {
                return com;
            }
        }
    }
    
    public String reorganizeString(String S) {
        int[] count = new int[26];
        int max = 0;
        char maxChar = '\0';
        int len = S.length();
        for (char c : S.toCharArray()) {
            count[c - 'a'] ++;
            if (count[c - 'a'] > max) {
                max = count[c - 'a'];
                maxChar = c;
            }
        }
        if (len % 2 == 0 && max > len / 2) { 
            return "";
        } else if (len % 2 == 1 && max > (len / 2 + 1)) {
            return "";   
        } else {
            PriorityQueue<Node> pq = new PriorityQueue();
            for (char c = 'a'; c <= 'z'; c ++) {
                if (count[c - 'a'] > 0) {
                    pq.offer(new Node(c, count[c - 'a']));
                }
            }
            StringBuilder sb = new StringBuilder();
            while (!pq.isEmpty()) {
                Node first = pq.poll();
                sb.append(first.c);
                if (!pq.isEmpty()) {
                    Node second = pq.poll();
                    sb.append(second.c);
                    if (second.freq > 1) {
                        pq.offer(new Node(second.c, second.freq - 1));
                    }
                }
                if (first.freq > 1) {
                    pq.offer(new Node(first.c, first.freq - 1));
                }
            }
            return sb.toString();
        }
    }
}