gpt4 book ai didi

java - 字符串和符号的压缩

转载 作者:行者123 更新时间:2023-11-30 03:59:38 24 4
gpt4 key购买 nike

我有大约 200 个字符的字符串,包括字符和符号我想使用任何算法压缩这个字符串...

请帮助我任何类型的程序、代码、算法

提前致谢

目前我正在使用它,但是当有符号时它显示数组索引超出范围。

**COMPRESSION**
byte[] encode(String txt, int bit){
int length = txt.length();
float tmpRet1=0,tmpRet2=0;
if(bit==6){
tmpRet1=3.0f;
tmpRet2=4.0f;
}else if(bit==5){
tmpRet1=5.0f;
tmpRet2=8.0f;
}
byte encoded[]=new byte[(int)(tmpRet1*Math.ceil(length/tmpRet2))];
char str[]=new char[length];
txt.getChars(0,length,str,0);
int chaVal = 0;
String temp;
String strBinary = new String("");
for (int i = 0;i<length; i++){
temp = Integer.toBinaryString(toValue(str[i]));
while(temp.length()%bit != 0){
temp="0"+temp;
}
strBinary=strBinary+temp;
}
while(strBinary.length()%8 != 0){
strBinary=strBinary+"0";
}
Integer tempInt =new Integer(0);
for(int i=0 ; i<strBinary.length();i=i+8){
tempInt = tempInt.valueOf(strBinary.substring(i,i+8),2);
encoded[i/8]=tempInt.byteValue();
}
return encoded;
}



**DECOMPRESSION** :

String decode(byte[] encoded, int bit){
String strTemp = new String("");
String strBinary = new String("");
String strText = new String("");
Integer tempInt =new Integer(0);
int intTemp=0;
for(int i = 0;i<encoded.length;i++){
if(encoded[i]<0){
intTemp = (int)encoded[i]+256;
}else
intTemp = (int)encoded[i];
strTemp = Integer.toBinaryString(intTemp);
while(strTemp.length()%8 != 0){
strTemp="0"+strTemp;
}
strBinary = strBinary+strTemp;
}
for(int i=0 ; i<strBinary.length();i=i+bit){
tempInt = tempInt.valueOf(strBinary.substring(i,i+bit),2);
strText = strText + toChar(tempInt.intValue());
}
return strText;
}

最佳答案

有一次,在我学习的时候,我的老师让我编写一个文本压缩器(很酷的作业)。基本思想是:如果每个字符都是 8 位,找到出现次数最多的字符并为其分配一个较短的值,同时为出现较少的字母分配一个较大的值。

例子:

A = 01010101B = 10101010

未压缩:AAAB - 01010101 01010101 01010101 10101010

压缩:

A 出现了 3 次(应该有更短的表示)B 出现了 1 次(应该有更长的表示)

A - 01

B - 10

结果:01 01 01 10

因此,您为每个字母生成一系列位,这样任何字母都不应具有可以与另一个字母匹配的表示形式。然后将生成的方案存储在压缩文件中。如果您想解压缩,只需从压缩文件中读取方案,然后开始一点一点地读取。

详情请看这里:http://web.stonehill.edu/compsci//LC/TEXTCOMPRESSION.htm

关于java - 字符串和符号的压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12703633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com