Skip to content

Commit ce31125

Browse files
committed
frequcy sort chars
1 parent 61cd331 commit ce31125

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/* ==============================================================================
2+
* 功能描述:FrequSort
3+
* 创 建 者:gz
4+
* 创建日期:2017/5/10 18:05:01
5+
* ==============================================================================*/
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
11+
//Given a string, sort it in decreasing order based on the frequency of characters.
12+
13+
//Example 1:
14+
15+
//Input:
16+
//"tree"
17+
18+
//Output:
19+
//"eert"
20+
21+
//Explanation:
22+
//'e' appears twice while 'r' and 't' both appear once.
23+
//So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
24+
//Example 2:
25+
26+
//Input:
27+
//"cccaaa"
28+
29+
//Output:
30+
//"cccaaa"
31+
32+
//Explanation:
33+
//Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
34+
//Note that "cacaca" is incorrect, as the same characters must be together.
35+
//Example 3:
36+
37+
//Input:
38+
//"Aabb"
39+
40+
//Output:
41+
//"bbAa"
42+
43+
//Explanation:
44+
//"bbaA" is also a valid answer, but "Aabb" is incorrect.
45+
//Note that 'A' and 'a' are treated as two different characters.
46+
namespace FrequencySortSln
47+
{
48+
/// <summary>
49+
/// FrequSort
50+
/// </summary>
51+
public class FrequSortSln
52+
{
53+
public string FrequencySort(string s)
54+
{
55+
Dictionary<char, int> freq = new Dictionary<char, int>();
56+
string[] buckets = new string[s.Length+1]; //索引用作字符个数,最大的个数索引也为最大
57+
//count char frequency
58+
foreach (var c in s)
59+
{
60+
if (!freq.ContainsKey(c))
61+
freq.Add(c, 1);
62+
else freq[c]++;
63+
}
64+
//put char to buckets
65+
foreach (var item in freq)
66+
{
67+
int n = item.Value;
68+
char c = item.Key;
69+
StringBuilder builder = new StringBuilder();
70+
buckets[n] += builder.Append(c, n).ToString();
71+
}
72+
StringBuilder builder2 = new StringBuilder();
73+
//form string
74+
for (int i = s.Length; i > 0; i--)
75+
{
76+
if (buckets[i] != null)
77+
builder2.Append(buckets[i]);
78+
}
79+
return builder2.ToString();
80+
}
81+
82+
}
83+
}

0 commit comments

Comments
 (0)