##LZW算法的压缩与解压
LZW压缩
#include <iostream>
#include <string>
#include <map>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {//对编码字符进行解码
int n;
map<int, string> LzwMap; //定义键值对存放<code,string>
cout<<"输入codes的个数"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++){//输入编码后的数字
cout<<"第"<<i+1<<"个数字(编码)";
cin>>a[i];
}
LzwMap[1]="A",LzwMap[2]="B",LzwMap[3]="C";//初始化词典分别对A/B/C进行1/2/3编码
string s="NIL";
int count=4;//新字符的编码
int k;
string str;
for(int i=0;i<n;i++){//对每一个给定的k进行查找
k=a[i];
map<int ,string>::iterator iter;
bool flag=false;
string value;
for(iter=LzwMap.begin();iter!=LzwMap.end();iter++){//搜素字典中键为k的值
if (iter->first==k){
flag=true;
value=iter->second;
break;
}
}
if(flag==true){//若存在字典中,则输出值
cout<<value<<"--";
}
if(s!="NIL"){//把S对应的字符和字典k中对应的字符串的第一个字符相加并存储在字典中
const char *p=value.data();
str=s+p[0];
LzwMap[count++]=str;
}
s=value;
}
return 0;
}
LZW解压
#include <iostream>
#include <string>
#include <map>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {//对编码字符进行解码
int n;
map<int, string> LzwMap; //定义键值对存放<code,string>
cout<<"输入codes的个数"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++){//输入编码后的数字
cout<<"第"<<i+1<<"个数字(编码)"<<endl;
cin>>a[i];
}
LzwMap[1]="A",LzwMap[2]="B",LzwMap[3]="C";//初始化词典分别对A/B/C进行1/2/3编码
string s="NIL";
int count=4;//新字符的编码
int k;
string str;
for(int i=0;i<n;i++){//对每一个给定的k进行查找
k=a[i];
map<int ,string>::iterator iter;
bool flag=false;
string value;
for(iter=LzwMap.begin();iter!=LzwMap.end();iter++){//搜素字典中键为k的值
if (iter->first==k){
flag=true;
value=iter->second;
break;
}
}
if(flag==true){//若存在字典中,则输出值
cout<<value<<"--";
}
if(s!="NIL"){//把S对应的字符和字典k中对应的字符串的第一个字符相加并存储在字典中
const char *p=value.data();
str=s+p[0];
LzwMap[count++]=str;
}
s=value;
}
return 0;
}