题
我有一个LZW压缩器/解压缩器在C写的。
在初始表包括ASCII字符,然后将每个现在串被保存到表由的前缀并一个的字符强>都保存在列表作为INT的。
我的压缩工作,但我的减压留下一些文字了。
在输入:
<title>Agile</title><body><h1>Agile</h1></body></html>
在输出I得到(注意丢失的 'e' 和 '<'):
<title>Agile</title><body><h1>Agil</h1></body>/html>
这是我使用的代码(相关部分):
void expand(int * input, int inputSize) {
// int prevcode, currcode
int previousCode; int currentCode;
int nextCode = 256; // start with the same dictionary of 255 characters
dictionaryInit();
// prevcode = read in a code
previousCode = input[0];
int pointer = 1;
// while (there is still data to read)
while (pointer < inputSize) {
// currcode = read in a code
currentCode = input[pointer++];
if (currentCode >= nextCode) printf("!"); // XXX not yet implemented!
currentCode = decode(currentCode);
// add a new code to the string table
dictionaryAdd(previousCode, currentCode, nextCode++);
// prevcode = currcode
previousCode = currentCode;
}
}
int decode(int code) {
int character; int temp;
if (code > 255) { // decode
character = dictionaryCharacter(code);
temp = decode(dictionaryPrefix(code)); // recursion
} else {
character = code; // ASCII
temp = code;
}
appendCharacter(character); // save to output
return temp;
}
您可以发现它?我很感激。
解决方案
您解码函数返回字符串的第一个字符。你需要这个角色,以便将它添加到字典中,但你应该的不的设置previousCode
它。所以,你的代码应该是这样的:
...
firstChar = decode(currentCode);
dictionaryAdd(previousCode, firstChar, nextCode++);
previousCode = currentCode;
...
不隶属于 StackOverflow