Appearance
0451-根据字符出现频率排序
https://leetcode.cn/problems/sort-characters-by-frequency
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:
"tree"
输出:
"eert"
解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
示例 2:
输入:
"cccaaa"
输出:
"cccaaa"
解释:
'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。
示例 3:
输入:
"Aabb"
输出:
"bbAa"
解释:
此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
注意'A'和'a'被认为是两种不同的字符。
思路
使用字段表缓存数据次数,记录最大值 递减最大值,按序输出字母个数
参考代码
csharp
public class Solution {
public string FrequencySort(string s) {
Dictionary<char,int> dict = new Dictionary<char,int>();
int max = 0;
for(int i=0; i<s.Length; i++){
if(!dict.ContainsKey(s[i])){
dict.Add(s[i],1);
}
else{
dict[s[i]]++;
}
max = Math.Max(max,dict[s[i]]);
}
//输出
StringBuilder sb = new StringBuilder();
while(max > 0){
foreach(char key in dict.Keys){
if(dict[key] == max){
//输出
for(int i=0; i<max; i++){
sb.Append(key.ToString());
}
}
}
max--;
}
return sb.ToString();
}
}
AlgoPress