# LZW减压算法

-压缩

```w = NIL;
while ( read a character k )
{
if wk exists in the dictionary
w = wk;
else
output the code for w;
w = k;
}```

-减压

```read a character k;
output k;
w = k;
while ( read a character k )
/* k could be a character or a code. */
{
entry = dictionary entry for k;
output entry;
add w + entry[0] to dictionary;
w = entry;
}```

```w       k       Dictionary          Output

-       b       -                   -
b       o       bo (256)            98 (b)
o       o       oo (257)            111 (o)
o       o       -                   -
oo      p       oop (258)           257 (oo)
p       -       -                   112 (p)```

output.txt的：
98
111
257
112

```w       k          entry        output       Dictionary
98 (b)                  b
b       111 (o)    o            o             bo (256)
o       257 (error)```

257(oo)尚未添加.任何人都可以看到我在哪里出错了因为我

-减压

```read a character k;
output k;
w = k;
while ( read a character k )
/* k could be a character or a code. */
{
if k exists in the dictionary
entry = dictionary entry for k;
output entry;
add w + entry[0] to dictionary;
w = entry;
else
output entry = w + firstCharacterOf(w);
w = entry;
}```

```w       k          entry        output       Dictionary
98 (b)                  b
b       111 (o)    o            o             bo (256)
o       257 (oo)                oo            oo(257)
oo      112(p)                  p```