public string Compression(string content) { HuffmanNote huffmanNote = CreateHuffmanTree(CreateWordWeightDictionary(content)); Dictionary <char, string> encodeDictionary = new Dictionary <char, string>(); CreateWordCodeDictionay(huffmanNote, "", encodeDictionary); StringBuilder sb = new StringBuilder(content.Length); foreach (var item in content) { sb.Append(encodeDictionary[item]); } string huffmanCode = sb.ToString(); HuffmanTreeInfo huffmanTreeInfo = new HuffmanTreeInfo(); huffmanTreeInfo.ZipCodeRemainder = huffmanCode.Substring(huffmanCode.Length - huffmanCode.Length % 8); huffmanTreeInfo.ZipCode = HuffmanCodeToByte(huffmanCode.Substring(0, huffmanCode.Length - huffmanCode.Length % 8)); huffmanTreeInfo.UnZipDictionary = CreateUnZipDictionary(encodeDictionary); return(ObjectToJson(huffmanTreeInfo)); }
private HuffmanNote CreateHuffmanTree(List <HuffmanNote> huffmanNoteList) { if (huffmanNoteList.Count == 1) { return(huffmanNoteList[0]); } var huffmanNoteListBySort = huffmanNoteList.OrderBy(o => o.Weight).ToList(); var minWeight2Note = huffmanNoteListBySort.Take(2).ToList(); huffmanNoteListBySort.RemoveAt(0); huffmanNoteListBySort.RemoveAt(0); var leftNote = minWeight2Note[0]; leftNote.HuffmanCode = '0'; var rightNote = minWeight2Note[1]; rightNote.HuffmanCode = '1'; var newNote = new HuffmanNote() { LeftNote = leftNote, RightNote = rightNote, Weight = leftNote.Weight + rightNote.Weight }; huffmanNoteListBySort.Add(newNote); return(CreateHuffmanTree(huffmanNoteListBySort)); }
private void CreateWordCodeDictionay(HuffmanNote huffmanNote, string HuffmanCode, Dictionary <char, string> encodeDictionary) { if (huffmanNote.LeftNote == null) { encodeDictionary[huffmanNote.Word] = HuffmanCode.Substring(1) + huffmanNote.HuffmanCode;//HuffmanCode.Substring(1) 为什么有这句呢 因为char默认值是\0 所以这里要把第一个字符\0去掉 return; } HuffmanCode += huffmanNote.HuffmanCode; CreateWordCodeDictionay(huffmanNote.LeftNote, HuffmanCode, encodeDictionary); CreateWordCodeDictionay(huffmanNote.RightNote, HuffmanCode, encodeDictionary); }