解题思路:使用map 将string里面的每个字符insert进去,之后需要对map的value进行一个降序,考虑到无法直接对map的值进行降序排列,所以把map 放到vector容器中,这样可以对vector直接排序,最后字符串转string,return 即可.
class Solution {
public:
string frequencySort(string s) {
//排序
if(s.length() == 0)
return "";
map<char,int>s_map;
for(int i = 0; i < s.length(); i++){
s_map[s[i]]++;
}
vector< pair<char,int> >s_res(s_map.begin(),s_map.end());
sort(s_res.begin(),s_res.end(),CmpByValue());
char s_c[s.length()];
int k = 0;
for(int i = 0; i < s_res.size(); i++){
for(int j = 0; j < s_res[i].second; j++){
//int k = s_res[i].second;
s_c[j+k] = s_res[i].first;
cout<<s_res[i].first<<" "<<endl;
}
k += s_res[i].second;
}
string res(s_c,s.length());
return res;
}
private:
struct CmpByValue {
bool operator()(const pair<char,int>& p1, const pair<char,int>& p2) {
return p1.second > p2.second;
}
};
};