多媒体技术 有损压缩算法之LZW编码算法

    Lempel_Ziv_Welch(LZW)算法利用了一种自适应的,基于字典的压缩技术。LZW编码器在接收数据时动态地创建字典。LZW在实现过程中不断将越来越长的重复条目插入字典中,然后将字符串的编码而不是字符串本身发送出去。  根据书上的伪代码(Pseudo code),也能很快的把程序写出。到此,多媒体第一次作业的四个算法都完成了。又可以有时间去刷题和搞搞java了。hiahiahia。。。。加油哦~孩子

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct dict{
    int  code;
    string str;
    dict(){}
};
dict dicts[100];

int main()
{
    //Initialize the dictionary
    int i,j,k,nCount;
    string s,c,str1,str2;
    ifstream infile("in.txt",ios::out);
    if(!infile)
    {
        cout<<"test文件不能打开"<<endl;
        return 0;
    }
    infile>>str1;
    i=0;
    while(str1[i])
    {
        dicts[i].str=str1[i];
        dicts[i].code=i+1;
        i++;
    }
    nCount=i;  //记录初始化的字典个数
    infile.close();
        //Input
    ifstream ifile("in1.txt",ios::out);
    ifile>>str2;
    i=0;
     bool flag=false;
     s=str2[i++];
    while(str2[i-1])  //要包括最后一个字符
    {
        string add_str;//存储 s+c
        c=str2[i];
        add_str+=s; add_str+=c;
        for(j=0; j<nCount; j++)
        {
               if(add_str==dicts[j].str)
               {
                   s=dicts[j].str;  //s=s+c
                   break;        
               }
        }
        if(j==nCount)
        {    //不在字典里
            for(k=0; k<nCount; k++)
             {  //output the code for s
                    if(dicts[k].str==s)
                    {       
                         cout<<dicts[k].code;
                         s=c;
                         break;
                    }
             }        
            //把s+c添加到字典里
              dicts[nCount].str=add_str;
              dicts[nCount].code=nCount+1;
               nCount++;
        }
        i++;
    } //while
    printf("\n");
    ifile.close();
    return 0;
}

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值