[LeetCode] 451. Sort Characters By Frequency
Given a string, sort it in decreasing order based on the frequency of characters.
'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.
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
Thoughts as following:
- Use an unordered_map to store the frequency of each char. The key is the character and the value is the frequency.
- Use one more map. The key is the frequency and the value is a vector<string> to store characters。The reason to use vector<string> to store characters is there might be more than one character have the same frequency. And the reason to use one more map is map will sort the data in increasing order based on key. Therefore, the highest frequent character will be the last element of map.
- Append all the characters to the string according their frequency.