-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0451-Sort-characters-by-frequency.cs
More file actions
49 lines (40 loc) · 1.15 KB
/
0451-Sort-characters-by-frequency.cs
File metadata and controls
49 lines (40 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0451.Sort_characters_by_frequency
{
public class _0451_Sort_characters_by_frequency
{
public string FrequencySort(string s)
{
Dictionary<char, int> dic = new Dictionary<char, int>();
foreach (char c in s)
{
if (dic.ContainsKey(c))
dic[c]++;
else
dic.Add(c, 1);
//if (!dic.TryAdd(c, 1)) dic[c]++;
}
StringBuilder sb = new StringBuilder();
int max = 0;
char ch = '0';
while (dic.Count != 0)
{
foreach (KeyValuePair<char, int> pair in dic)
{
if (pair.Value > max)
{
max = pair.Value;
ch = pair.Key;
}
}
dic.Remove(ch);
for (int i = 0; i < max; i++)
sb.Append(ch);
max = 0;
}
return sb.ToString();
}
}
}