[LeetCode] 767. Reorganize String

Problem

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.c++

If possible, output any possible result. If not possible, return the empty string.app

Example 1:ui

Input: S = "aab"
Output: "aba"
Example 2:code

Input: S = "aaab"
Output: ""
Note:string

S will consist of lowercase letters and have length in range [1, 500].io

Solution

class Solution {
    public String reorganizeString(String S) {
        int n = S.length();
        int[] cnt = new int[128];
        char mc = 'a';
        for (char c : S.toCharArray()) {
            cnt[c]++;
            mc = (cnt[c] > cnt[mc]) ? c : mc;
        }
        if (cnt[mc] == 1) {
            return S;
        }
        if (cnt[mc] > (n+1)/2) {
            return "";
        }
        StringBuilder[] sb = new StringBuilder[cnt[mc]];
        for (int i = 0; i < sb.length; i ++) {
            sb[i] = new StringBuilder();
            sb[i].append(mc);
        }
        int k = 0;
        for (char c = 'a'; c <= 'z'; c++) {
            while (c != mc && cnt[c] > 0) {
                sb[k++].append(c);
                cnt[c]--;
                k %= sb.length;
            }
        }
        for (int i = 1; i < sb.length; i++) {
            sb[0].append(sb[i]);
        }
        return sb[0].toString();
    }
}
相關文章
相關標籤/搜索