In today’s challenge, we need to sort a given String according to the frequencies of each character present in descending order.
addfffg -> fffddag or fffddga
We first calculate the frequency of each character(a-z and A-Z) in the String and put it in our HashMap.
Then, we sort the HashMap according to its values(frequency). Then we traverse through the sorted list while generating the String(repeating each character according to its frequency in the original String). The String generated is our answer.
The full walkthrough guide, and the code is present below.
class Solution{public String frequencySort(String s) {
HashMap<Character,Integer> hmap = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
hmap.put(c, hmap.getOrDefault(c, 0)+ 1);
}
List<Map.Entry<Character, Integer>> listOfEntries =
new ArrayList<Map.Entry<Character, Integer>> (hmap.entrySet());
Collections.sort(listOfEntries, new Comparator<Map.Entry<Character, Integer> >() {
public int compare(Map.Entry<Character, Integer> e1,
Map.Entry<Character, Integer> e2)
{
return (e2.getValue()).compareTo(e1.getValue());
}
});
String sortedString = "";
for (Map.Entry<Character, Integer> entry : listOfEntries) {
sortedString +=String.valueOf(entry.getKey()).repeat(entry.getValue());
}
return sortedString;
}
}
Thank you for reading!