1
\$\begingroup\$

Here I'm posting my Java code for the Reorganize String problem on LeetCode. If you have time and would like to review, please do so, I'd appreciate that.

On LeetCode, we are only allowed to change the argument names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).

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.

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: "" Note:

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

Java

class Solution {
    public String reorganizeString(String baseString) {
        int[] charMap = initializeCharMap26(baseString);
        int max = 0;
        int letter = 0;

        for (int iter = 0; iter < charMap.length; iter++)
            if (charMap[iter] > max) {
                max = charMap[iter];
                letter = iter;
            }

        if (max > ((-~baseString.length()) >> 1))
            return "";

        char[] reorganized = new char[baseString.length()];
        int index = 0;

        while (charMap[letter] > 0) {
            reorganized[index] = (char) (letter + 97);
            index += 2;
            charMap[letter]--;
        }

        for (int iter = 0; iter < charMap.length; iter++) {
            while (charMap[iter] > 0) {
                if (index >= reorganized.length)
                    index = 1;

                reorganized[index] = (char) (iter + 97);
                index += 2;
                charMap[iter]--;
            }
        }

        return String.valueOf(reorganized);
    }

    private int[] initializeCharMap26(String baseString) {
        int[] charMap = new int[26];

        for (int i = 0; i < baseString.length(); i++)
            charMap[baseString.charAt(i) - 97]++;

        return charMap;
    }
}

Reference

767. Reorganize String (Problem)

767. Reorganize String (Solution)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.