【发布时间】:2020-08-26 11:57:38
【问题描述】:
我的任务:
- 从用户那里获取字符串
- 找出字符串中每个字符重复的次数
- 找出重复次数最少的两个字符,将它们的频率相加,然后将它们加上它们的频率之和
- 将这个新的总和重新添加到列表中,无论它现在去哪里,更高
- 重复这些步骤,直到得到一棵霍夫曼树!
我的代码:
class Program
{
static void Main(string[] args)
{
HuffmanTree.GetValue();
}
}
class HuffmanTree
{
public static void GetValue()
{
Console.WriteLine("Write a string to be encoded"); //Here we are asking the user to input a string
string encodeme = Console.ReadLine(); // here the user inputs their string, which gets declared as the variable "encodeme"
Dictionary<char, int> timesRepeated = new Dictionary<char, int>();
foreach (char ch in encodeme.Replace(" ", string.Empty))
{
if (timesRepeated.ContainsKey(ch))
{
timesRepeated[ch] = timesRepeated[ch] + 1;
}
else
{
timesRepeated.Add(ch, 1);
}
}
foreach (var item in timesRepeated.Keys)
{
Console.WriteLine(item + " : " + timesRepeated[item]);
}
Console.ReadKey();
}
}
class Node
{
}
所以我试图将字典值“重复次数”按降序排序,这样当它打印出字符重复的次数时,它会按降序显示这些值。
例如,如果我输入了字符串“BOOOM”
O = 3
B = 1
M = 1
此刻它说:
B = 1
O = 3
M = 1
我不知道该怎么做!!!
【问题讨论】:
-
this 回答你的问题了吗?
标签: c#