Skip to content

Instantly share code, notes, and snippets.

@fakruboss
Last active June 16, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fakruboss/1395a7a92457667f5fa5de11d1a95c08 to your computer and use it in GitHub Desktop.
Save fakruboss/1395a7a92457667f5fa5de11d1a95c08 to your computer and use it in GitHub Desktop.
class Solution {
public static String rearrangeCharacters(String str) {
Map<Character, Integer> freq = new HashMap<>();
for (char c : str.toCharArray()) freq.put(c, freq.getOrDefault(c, 0) + 1);
List<Map.Entry<Character, Integer>> freqList = new ArrayList<>(freq.entrySet());
// freqList.sort(Map.Entry.comparingByValue());
freqList.sort((e1, e2) -> e2.getValue() - e1.getValue());
Map<Character, Integer> sortedFreq = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> entry : freqList) sortedFreq.put(entry.getKey(), entry.getValue());
int n = str.length();
char[] result = new char[n];
int index = 0;
for (Map.Entry<Character, Integer> entry : sortedFreq.entrySet()) {
char key = entry.getKey();
int value = entry.getValue();
while (value -- > 0) {
result[index % n] = key;
index += 2;
}
}
return new String(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment