1. 程式人生 > >LeetCode-Reorganize String

LeetCode-Reorganize String

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