Leetcode 451. Sort Characters By
2018-09-01 本文已影响1人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Sort Characters By Frequency2. Solution
bool compare(pair<char, int>& a, pair<char, int>& b) {
return a.second > b.second;
}
class Solution {
public:
string frequencySort(string s) {
map<char, int> stat;
for(int i = 0; i < s.length(); i++) {
stat[s[i]]++;
}
vector<pair<char, int>> values;
for(auto val: stat) {
values.push_back(val);
}
sort(values.begin(), values.end(), compare);
string result;
for(auto val : values) {
for(int i = 0; i < val.second; i++) {
result += val.first;
}
}
return result;
}
};