给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入: “tree”
输出: “eert”
解释: 'e’出现两次,'r’和’t’都只出现一次。 因此’e’必须出现在’r’和’t’之前。此外,"eetr"也是一个有效的答案。 示例
2:输入: “cccaaa”
输出: “cccaaa”
解释: 'c’和’a’都出现三次。此外,"aaaccc"也是有效的答案。 注意"cacaca"是不正确的,因为相同的字母必须放在一起。 示例
3:输入: “Aabb”
输出: “bbAa”
解释: 此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。 注意’A’和’a’被认为是两种不同的字符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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.
C++,简单遍历,20ms,78%
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> m1;
for (char i : s) {
m1[i]++; //统计<词,频次>
}
multimap<int, char> m2;
for (auto it = m1.begin(); it != m1.end(); ++it) {
m2.insert({ it->second,it->first }); //反转储存<频次,词>,自动排序
}
string s1(s);
int i = 0; //输出
for (auto it2 = m2.rbegin(); i < s.size()&&it2 != m2.rend(); ++it2) {
int temp = it2->first;
while (temp != 0) {
s1[i]=(it2->second);
++i;
--temp;
}
}
return s1;
}
};