1. 程式人生 > >LeetCode: 767 Reorganize String

LeetCode: 767 Reorganize String

題目: 767 Reorganize String (https://leetcode.com/problems/reorganize-string/)

每次取當前出現頻率最高的兩個字母拼接在字串上。直到PriorityQueue中元素的數量只有一個或者沒有。如果只有一個且他還有大於1的頻率,就說明這個字元創無法Reorganize。

class Solution {
    public String reorganizeString(String S) {
        String result = "";
        char[] chars = S.toCharArray();

        Map<Character, Integer> appearMap = new HashMap<>();
        for (char c : chars) {
            int appearCount = appearMap.containsKey(c) ? appearMap.get(c) : 0;
            appearCount++;
            appearMap.put(c, appearCount);
        }

        PriorityQueue<int[]> queue = new PriorityQueue<>((x, y) -> y[1] - x[1]); // cool
        for (Map.Entry<Character, Integer> entry : appearMap.entrySet()) {
            queue.add(new int[]{entry.getKey(), entry.getValue()});
        }

        while (queue.size() > 1) {
            int[] head = queue.poll();
            int[] second = queue.poll();
            result += (char) head[0];
            result += (char) second[0];
            if (--head[1] > 0) {
                queue.add(head);
            }
            if (--second[1] > 0) {
                queue.add(second);
            }
        }

        if (!queue.isEmpty()) {
            int[] head = queue.poll();
            if (head[1] > 1) {
                return "";
            } else {
                result += (char) head[0];
            }
        }
        return result;
    }
}