Description:
Given a string, sort it in decreasing order based on the frequency of characters.
Input: "tree" Output: "eert"这道题看上去是不是感觉很简单?依照习惯的思路,也就是先统计每个字符出现的次数然后根据其次数排序(使用sort)一下不就出来了么?殊不知,其时间复杂度为O(nlog(n)),那么有办法将其复杂度降到 O(n)么?当然有,这也是写这篇文章记录的意义吧(注:这个巧妙的方法当然不是我想出来的,借鉴大神之手)。下面将列出第一种和第二种。
class Solution1 {
public:
string frequencySort(string s) {
int counts[256];
for (auto& ch : s) counts[ch]++;
sort(s.begin(), s.end(), [&](char a, char b) {
return counts[a] > counts[b] || (counts[a] == counts[b] && a < b);
});
return s;
}
};
class Solution2 {
public:
string frequencySort(string s) {
unordered_map<char,int> freq;
vector<string> bucket(s.size()+1, "");
string res;
for(char c:s) freq[c]++;
for(auto& it:freq) {
int n = it.second;
char c = it.first;
bucket[n].append(n, c);
}
for(int i=s.size(); i>0; i--) {
if(!bucket[i].empty())
res.append(bucket[i]);
}
return res;
}
};
首先是把字符存到无序map中,然后根据每个key的value(即每个字符的出现次数)将其存放在一个vector<string>中,每个元素中存放若干相同字符,value越大,那么他在
vector<string>中的位置越靠后,最后逆序将每个元素追加为结果输出。(完美)