451 - Sort Characters By Frequency
#medium
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 1:
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.
Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
class Solution {
public:
string frequencySort(string s) {
vector<pair<int,char>> v; // count, letter: for sorting the data.
map<char,int> mp; // letter, count: for saving the data.
for ( int i = 0; i < s.size(); i++ ) {
mp[s[i]]++;
}
for ( auto it = mp.begin(); it != mp.end(); it++ ) {
v.push_back( {it->second, it->first} );
}
sort(v.rbegin(), v.rend() ); // 由大到小
string result = "";
for ( int i = 0; i < v.size(); i++ ) {
pair <int, char> temp = v[i];
for ( int j = 0; j < temp.first; j++ ) {
result += temp.second;
}
}
return result;
}
};