451. Sort Characters By Frequency
题目描述:
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input: "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.
Example 2:
Input: "cccaaa" Output: "cccaaa" Explanation: 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.
Example 3:
Input: "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.
算法描述:
根据题意,给出一个字符串,我们将对它进行排序,按照字符串中各个字符的出现频率递减排序,出现次数越少排在越后面,最后返回一个结果字符串。
首先,我们将定义一个 map容器,map可以提供一对一的数据映射能力(其中第一个可以称之为关键字,每个关键字只能在map中出现一次,第二个可以称之为映射的值,即该关键字的值),由于map的这个特性,我们在这道题中可以充分的运用以方便统计给出字符串中各个字符的出现个数。完成映射之后,我们构造临时容器 temp ,将map中的元素填装进 vector 。
第二步,我们应用 sort 函数对 vector 进行排序,按照字符在字符串中出现的次数递减排序。
最后,我们根据出现次数,构造字符串。
代码:
class Solution {
public:
string frequencySort(string s) {
string ans;
vector<pair<char,int>> temp;
map<char,int> m;
for(int i=0; i<s.size(); i++){
m[s[i]]++;
}
for(auto it:m){
pair<char,int> p(it.first,it.second);
temp.push_back(p);
}
sort(temp.begin(),temp.end(),[](pair<char,int> a, pair<char,int> b){
return a.second>b.second;
});
for(int i=0; i<temp.size(); i++){
string str(temp[i].second,temp[i].first);
ans+=str;
}
return ans;
}
};