早教吧 育儿知识 作业答案 考试题库 百科 知识分享

C语言霍夫曼编码本题要求各函数的参数使用指针假设字母a、b、c、d、e、f的霍夫曼编码分别是1、00、011、0100、01010、01011。那么字符串“abcdef”的编码显然就是字符串“10001101000101001011”。

题目详情
C 语言 霍夫曼编码
本题要求各函数的参数使用指针
假设字母a、b、c、d、e、f的霍夫曼编码分别是1、00、011、0100、01010、01011。那么字符串“abcdef”的编码显然就是字符串“10001101000101001011”。
(1)编写编码函数实现对字符串“abcdef”的编码,显示编码结果。
(2)编写译码函数对刚才得到的编码进行译码,显示译码结果。
(3)假设有一段编码“010111011010100100010010100”,请对其译码,并显示译码结果。
▼优质解答
答案和解析
#include <stdio.h>
#include <string.h>

/*
本题要求各函数的参数使用指针

假设字母a、b、c、d、e、f的霍夫曼编码分别是1、00、011、0100、01010、01011。那么字符串“abcdef”的编码显然就是字符串“10001101000101001011”。

(1)编写编码函数实现对字符串“abcdef”的编码,显示编码结果。
(2)编写译码函数对刚才得到的编码进行译码,显示译码结果。
(3)假设有一段编码“010111011010100100010010100”,请对其译码,并显示译码结果。
*/

char hufman[6][10] = {
{"a1"},
{"b00"},
{"c011"},
{"d0100"},
{"e01010"},
{"f01011"},
};


void code(char *src,char *dest)
{
int i;
int len = 0;
while(*src != '\0')
{
for(i=0;i<6;i++)
{
if(*src == hufman[i][0])
{
strcpy(dest + len,hufman[i]+1);
len += strlen(hufman[i]+1);
break;
}
}
src ++;
}
}


void decode(char *src,char *dest)
{
int i;
int len = 0;
while(*src != '\0')
{
for(i=0;i<6;i++)
{
if(strncmp(src,hufman[i]+1,strlen(hufman[i]+1)) == 0)
{
dest[len++] = hufman[i][0];
src += strlen(hufman[i]+1);
break;
}
}
}
dest[len] = 0;
}


int main(int argc,char *argv[])
{
char *str = "abcdef";
char *str1 = "010111011010100100010010100";
char res[100] = {0};
char decodeRes[20];
code(str,res);
printf("%s\n",res);

decode(res,decodeRes);

printf("%s\n",decodeRes);

decode(str1,decodeRes);

printf("%s\n",decodeRes);

}

看了C语言霍夫曼编码本题要求各函数...的网友还看了以下: