题意:按字符出现频率降序输出字符。
思路:用hash实现O(1)插入和查找。
class Solution {
public:
string frequencySort(string s) {
map<char, int> m;
for(int i = 0; i < s.length(); ++ i) {
m[s[i]] ++;
}
string re;
int mmax = -1;
while(mmax) {
mmax = 0;
std::map<char, int>::iterator it;
std::map<char, int>::iterator mm;
for(it = m.begin(); it != m.end(); ++ it) {
if(mmax < it->second) {
mm = it;
mmax = it->second;
}
}
if(mmax == 0) break;
while(mm->second) {
re += mm->first;
mm->second --;
}
}
//cout << re << endl;
return re;
}
};