using System.Collections.Generic;
|
|
namespace iWareModel
|
{
|
public class LZW
|
{
|
private Dictionary<string, int> myBaseDir;
|
|
private Dictionary<byte, int> myBaseByteDir;
|
|
public LZW(){}
|
|
public LZW(Dictionary<string, int> myBaseDir) { this.myBaseDir = myBaseDir;}
|
|
public LZW(Dictionary<byte, int> myBaseByteDir) { this.myBaseByteDir = myBaseByteDir; }
|
|
/// <summary>
|
/// LZW压缩算法
|
/// </summary>
|
/// <param name="source"></param>
|
/// <returns></returns>
|
public List<int> Compress(string source)
|
{
|
var nextValue = 0;
|
var res = new List<int>();
|
var dict = new Dictionary<string, int>();
|
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;
|
}
|
|
/// <summary>
|
/// LZW解压算法
|
/// </summary>
|
/// <param name="source"></param>
|
/// <returns></returns>
|
public string Decompress(List<int> destination)
|
{
|
var nextValue = 0;
|
var res = string.Empty;
|
var dict = new Dictionary<int, string>();
|
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;
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
}
|