Reorganize String

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.

Example 1:

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

Input: S = "aaab" Output: ""

Solution:

string reorganizeString(string S) { if (S.empty()) return ""; int arr[26] = {0}; for (auto ch: S) arr[ch - 'a']++;

string ans(1, S.front());
int i = 1;
while (i < S.size()) {
    char candidate = ' ';
    for (int j=0; j<26; j++) {
        if (ans[i-1] - 'a' != j && arr[j] > 0) {
            arr[j] -= 1;
            candidate  = j + 'a';
            break;
        }
    }

    if (candidate == ' ') return "";
    ans += candidate;
    i += 1;
}

return ans;

}

results matching ""

    No results matching ""