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;
    }
}

猜你喜欢

转载自blog.csdn.net/majinliang1234/article/details/83083397