LeetCode Sort Characters By Frequency

LeetCode 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.

把一个字符串中的字符按出现频率重新排序并输出。 简单题,因为ascii的字符有128个,所以构造一个128长的hash表,先统计一下每个字符出现的次数,然后对频率排个序,最后按频率从高到低重新构造字符串。 完整代码如下: [cpp] typedef struct Character{ char c; int cnt; bool operator<(const Character& ch) const { return this->cnt < ch.cnt; } }; class Solution { public: string frequencySort(string s) { vector<Character> hash(128); for (int i = 0; i < s.size(); ++i) { hash[s[i]].c = s[i]; ++hash[s[i]].cnt; } sort(hash.begin(), hash.end()); string ans = ""; for (int i = 127; i >=0; –i) { if (hash[i].cnt == 0)break; ans += string(hash[i].cnt, hash[i].c); } return ans; } }; [/cpp] 本代码提交AC,用时23MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *