AlgoMaster Logo

Reorganize String

s=aab
1public String reorganizeString(String s) {
2    // Count frequencies
3    int[] count = new int[26];
4    for (char c : s.toCharArray()) {
5        count[c - 'a']++;
6    }
7
8    // Find the character with the maximum frequency
9    int maxCount = 0;
10    char maxChar = 'a';
11    for (int i = 0; i < 26; i++) {
12        if (count[i] > maxCount) {
13            maxCount = count[i];
14            maxChar = (char) (i + 'a');
15        }
16    }
17
18    // Check if reorganization is possible
19    if (maxCount > (s.length() + 1) / 2) {
20        return "";
21    }
22
23    char[] result = new char[s.length()];
24    int index = 0;
25
26    // Place the highest frequency character at even positions
27    while (count[maxChar - 'a'] > 0) {
28        result[index] = maxChar;
29        index += 2;
30        count[maxChar - 'a']--;
31    }
32
33    // Fill other characters
34    for (int i = 0; i < 26; i++) {
35        while (count[i] > 0) {
36            if (index >= result.length) {
37                index = 1;
38            }
39            result[index] = (char) (i + 'a');
40            index += 2;
41            count[i]--;
42        }
43    }
44
45    return new String(result);
46}
0 / 24
Input String:aab