Hey! It's day 5 of 10 days coding challenge with I4G. Today's challenge was to write a code that sorts characters by frequency.
Thought Process:
Understanding of problem: The problem here is to write a code that checks through a string and sorts each character based on their frequency of occurrence
Solution: In order to achieve this, I utilized some java classes such as HashMap and StringBuilder. The HashMap is java classes uses the Map interface to store key pair values. In this task I used it to iterate through the given string and store each character and its count in a Map. The character map was then sorted based on frequency and then the string builder was used to build the result back to a string.
Algorithm:
- Instantiate the string builder to builder
- Instantiate the HashMap using the Map interface to charMap as a key pair of Character and Integer
- User for loop to traverse through the string and store it in the charMap
- Sort the character map for each key-value pairs
- Using another for loop iterate through the key-value pair and append to the string builder.
- Return the builder in string format
Checkout the code here: https://leetcode.com/submissions/detail/808336602/
Top comments (0)