LeetCode-Reorganize String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83311553

一、Description

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.

题目大意:

给定一个字符串S,检查S中的所有字母是否存在相邻字母相同的,如果存在,则重新排布S中的字母,使得相邻字母不得相同,如果无法实现,则返回空字符串。

Example 1:

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

Example 2:

Input: S = "aaab"
Output: ""

二、Analyzation

这个题试了很多方法,要么超时,要么就是逻辑比较混乱,最后决定用优先队列来实现。其中定义一个类,包含了字母和字母出现的次数,通过自定义优先队列的排序规则,将字母出现次数多的优先排在前面,通过一个while循环不断地将队列中的字母取出来并交替排列,如此下去即得所求。


三、Accepted code

class Word {
    char letter;
    int count;

    public Word(char letter, int count) {
        this.letter = letter;
        this.count = count;
    }
}
class Solution {
    public String reorganizeString(String S) {
        int[] alp = new int[26];
        int max = 0;
        PriorityQueue<Word> queue = new PriorityQueue<>(new Comparator<Word>() {
            @Override
            public int compare(Word o1, Word o2) {
                return o2.count - o1.count;
            }
        });
        for (int i = 0; i < S.length(); i++) {
            alp[S.charAt(i) - 'a']++;
        }
        for (int i = 0; i < 26; i++) {
            if (max < alp[i]) {
                max = alp[i];
            }
            if (alp[i] > 0) {
                queue.offer(new Word((char) (i + 'a'), alp[i]));
            }
        }
        if (max > S.length() - max + 1) {
            return "";
        }
        String result = "";
        while (queue.size() >= 2) {
            Word word1 = queue.poll();
            Word word2 = queue.poll();
            result += word1.letter;
            result += word2.letter;
            word1.count--;
            word2.count--;
            if (word1.count > 0) {
                queue.offer(word1);
            }
            if (word2.count > 0) {
                queue.offer(word2);
            }
        }
        if (queue.size() > 0) {
            result += queue.poll().letter;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83311553