1. 程式人生 > 其它 >LuoguP4419 [COCI2017-2018#1] Cezar 題解

LuoguP4419 [COCI2017-2018#1] Cezar 題解

給定一個字串S,檢查是否能重新排布其中的字母,使得兩相鄰的字元不同。

若可行,輸出任意可行的結果。若不可行,返回空字串。

示例1:

輸入: S = "aab"
輸出: "aba"
示例 2:

輸入: S = "aaab"
輸出: ""

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/reorganize-string
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

class Solution {

    private int[] findTop2(int[] cnt) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(cnt[o1], cnt[o2]);
            }
        });

        for (int i = 0; i < cnt.length; ++i) {
            if (cnt[i] != 0) {
                if (queue.size() != 2) {
                    queue.offer(i);
                } else {
                    if (cnt[queue.peek()] < cnt[i]) {
                        queue.poll();
                        queue.offer(i);
                    }
                }
            }
        }

        if (queue.size() == 2) {
            int left = queue.poll(), right = queue.poll();
            if (cnt[left] == cnt[right]) {
                return new int[]{Math.min(left, right), Math.max(left, right)};
            }
            return new int[]{right, left};
        } else {
            return new int[]{queue.poll(), -1};
        }
    }

    public String reorganizeString(String s) {
        int limit = s.length() / 2 + (s.length() & 1);
        int[] cnt = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            cnt[s.charAt(i) - 'a']++;
            if (cnt[s.charAt(i) - 'a'] > limit) {
                return "";
            }
        }

        char[] ans = new char[s.length()];
        int index = 0;
        while (index < s.length()) {
            int[] top2 = findTop2(cnt);
            ans[index] = (char) (top2[0] + 'a');
            cnt[top2[0]]--;
            if (top2[1] != -1) {
                ans[index + 1] = (char) (top2[1] + 'a');
                cnt[top2[1]]--;
            }
            index += 2;
        }

        return new String(ans);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().reorganizeString(in.next()));
        }
    }
}
心之所向,素履以往 生如逆旅,一葦以航