Difan Chen

Posted on

# Leetcode 451. Sort Characters By Frequency

https://leetcode.com/problems/sort-characters-by-frequency/

## Problem Statement

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Example

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

## Solution

``````    public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : s.toCharArray()) {
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Collections.sort(list, (a, b) -> b.getValue() - a.getValue());
StringBuilder sb = new StringBuilder();
for (Map.Entry<Character, Integer> entry : list) {
for (int i = 0; i < entry.getValue(); i++) {
sb.append(entry.getKey());
}
}
return sb.toString();
}
``````

DEV Community

Timeless DEV post...

## Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.