Sort Characters By Frequency

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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.
LeetCode Problem - 451
class Solution {
public String frequencySort(String s) {
// Create a HashMap to store the frequency of each character in the string
Map<Character, Integer> map = new HashMap<>();
// Loop through the string and count the frequency of each character
for (int i = 0; i < s.length(); i++) {
// If the character is already in the map, increase its count by 1
// Otherwise, add the character to the map with a count of 1
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
// Create a list of characters based on the keys from the map
List<Character> list = new ArrayList<>(map.keySet());
// Sort the list of characters by their frequency in descending order
Collections.sort(list, (a, b) -> map.get(b) - map.get(a));
// Use a StringBuilder to construct the final sorted string
StringBuilder sb = new StringBuilder();
// For each character in the sorted list, append it to the StringBuilder
// the number of times it appears in the original string
for (char currentChar : list) {
int freq = map.get(currentChar);
while (freq > 0) {
sb.append(currentChar);
freq--;
}
}
// Convert the StringBuilder to a string and return it as the result
return sb.toString();
}
}




