using System.Collections.Generic; namespace iWareModel { public class LZW { private Dictionary myBaseDir; private Dictionary myBaseByteDir; public LZW(){} public LZW(Dictionary myBaseDir) { this.myBaseDir = myBaseDir;} public LZW(Dictionary myBaseByteDir) { this.myBaseByteDir = myBaseByteDir; } /// /// LZW压缩算法 /// /// /// public List Compress(string source) { var nextValue = 0; var res = new List(); var dict = new Dictionary(); if (myBaseDir != null) { foreach (var item in myBaseDir) { dict.Add(item.Key, item.Value); if(item.Value > nextValue) { nextValue = item.Value; } } } nextValue += 1; var prefix = ""; for (var i = 0; i < source.Length; i++ ) { if (dict.ContainsKey(prefix + source[i])) { prefix += source[i]; } else { res.Add(dict[prefix]); dict.Add(prefix + source[i], nextValue++); prefix = source[i].ToString(); } } if (dict.ContainsKey(prefix)) { res.Add(dict[prefix]); } dict = null; return res; } /// /// LZW解压算法 /// /// /// public string Decompress(List destination) { var nextValue = 0; var res = string.Empty; var dict = new Dictionary(); if (myBaseDir != null) { foreach (var item in myBaseDir) { dict.Add(item.Value, item.Key); if (item.Value > nextValue) { nextValue = item.Value; } } } nextValue += 1; var prefix = string.Empty; var current = string.Empty; var oCode = -1; var nCode = -1; for (var i = 0; i < destination.Count; i++) { nCode = destination[i]; if(dict.ContainsKey(nCode)) { prefix = dict[nCode]; } else { prefix = dict[oCode] + current; } res += prefix; current = prefix[0].ToString(); if(dict.ContainsKey(oCode)) { dict.Add(nextValue++, dict[oCode] + current); } oCode = nCode; } dict = null; return res; } } }