public String frequencySort(String s) {
// use array to save the char and it's frequency
int[] charToFre = new int[256];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
charToFre[c]++;
}
PriorityQueue<Integer> sortResult = new PriorityQueue<>
((a, b) -> (charToFre[a] == charToFre[b] ? a - b : charToFre[b] - charToFre[a]));
for (int i = 0; i < 256; i++) {
if (charToFre[i] > 0) {
sortResult.add(i);
}
}
// the int should be convert to char!!!
StringBuilder result = new StringBuilder();
while (!sortResult.isEmpty()) {
int i = sortResult.poll();
for (int j = 0; j < charToFre[i]; j++) {
result.append((char)(i));
}
}
return result.toString();
}