Miscellaneous problems · Exercise 86 of 100
Encode text with LZW
Start with a dictionary that assigns a code to each input symbol, and read the longest phrase already in the dictionary. Emit its code so the whole phrase can be represented by one number. If another symbol follows, add the phrase plus that symbol under the next free code, then begin the next phrase at that symbol.
Try it yourself
Encode ABAB with LZW starting with A = 1 and B = 2. New codes start at 3 and increase by one. What is the last code emitted?
One-step hint
Keep a table of phrases as you scan ABAB. Whenever an extension is new, enter it in the table, then restart at the letter that triggered the addition.
Worked solution
- At the start, AB is new, so emit 1 for A and add AB under code 3. At the next position, BA is new, so emit 2 for B and add BA under code 4.
- The remaining text is AB, which the dictionary now contains. Emit its code 3 to finish.