如何實現C#中的LZW壓縮演算法
引言:
隨著資料的不斷增長,資料的儲存和傳輸成為了一項重要任務。 LZW(Lempel-Ziv-Welch)壓縮演算法是一種常用的無損壓縮演算法,可以有效地減少資料的體積。本文將介紹如何在C#中實作LZW壓縮演算法,並給出具體的程式碼範例。
using System; using System.Collections.Generic; using System.Text; class LZWCompression { public static List<int> Compress(string data) { Dictionary<string, int> dictionary = new Dictionary<string, int>(); List<int> compressedData = new List<int>(); int currentCode = 256; for (int i = 0; i < 256; i++) { dictionary.Add(((char)i).ToString(), i); } string currentString = ""; foreach (char c in data) { string newString = currentString + c; if (dictionary.ContainsKey(newString)) { currentString = newString; } else { compressedData.Add(dictionary[currentString]); dictionary.Add(newString, currentCode); currentCode++; currentString = c.ToString(); } } if (currentString != "") { compressedData.Add(dictionary[currentString]); } return compressedData; } public static string Decompress(List<int> compressedData) { Dictionary<int, string> dictionary = new Dictionary<int, string>(); StringBuilder decompressedData = new StringBuilder(); int currentCode = 256; for (int i = 0; i < 256; i++) { dictionary.Add(i, ((char)i).ToString()); } int previousCode = compressedData[0].Value.ToString(); decompressedData.Append(dictionary[previousCode]); for (int i = 1; i < compressedData.Count; i++) { int currentCode = compressedData[i]; if (dictionary.ContainsKey(currentCode)) { decompressedData.Append(dictionary[currentCode]); string newEntry = dictionary[previousCode] + dictionary[currentCode][0]; dictionary.Add(currentCode, newEntry); previousCode = currentCode; } else { string newEntry = dictionary[previousCode] + dictionary[previousCode][0]; decompressedData.Append(newEntry); dictionary.Add(currentCode, newEntry); previousCode = currentCode; } } return decompressedData.ToString(); } }
下面是LZW壓縮演算法的使用範例:
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string originalData = "AAAAABBBBCCCCCDDDDDEE"; Console.WriteLine("原始数据: " + originalData); List<int> compressedData = LZWCompression.Compress(originalData); Console.WriteLine("压缩后的数据: " + string.Join(",", compressedData)); string decompressedData = LZWCompression.Decompress(compressedData); Console.WriteLine("解压缩后的数据: " + decompressedData); Console.ReadLine(); } }
以上程式碼範例中,我們使用LZWCompression
類別進行了資料的壓縮與解壓縮,其中壓縮使用了Compress
方法,解壓縮使用了Decompress
方法。
結論:
本文介紹如何在C#中實作LZW壓縮演算法,並給出了具體的程式碼範例。 LZW壓縮演算法是一種常用且有效的無損壓縮演算法,可以幫助我們減少資料的體積,提高資料的儲存和傳輸效率。
以上是如何實作C#中的LZW壓縮演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!