-
Notifications
You must be signed in to change notification settings - Fork 0
/
LZW.java
79 lines (61 loc) · 1.8 KB
/
LZW.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.ArrayList;
import java.util.List;
public class LZW {
private List dictionary;
public LZW(){
this.dictionary = new ArrayList();
this.dictionary.add("#");
for(int i=0;i<256;i++)
this.dictionary.add(String.valueOf((char)(i)));
}
private String toBinary(long n,long wordSize) {
String res = Integer.toBinaryString((int)n),buffer = "";
return String.format("%"+ (int)(wordSize) + "s",res).replace(' ','0');
}
public String compress(String input) {
String output = "", buffer;
long i=0,j, wordSize;
while(i<input.length()) {
wordSize =(long) Math.ceil( Math.log(dictionary.size()) / Math.log(2)) ;
j = i;
buffer = "";
while(j<input.length()) {
if(!dictionary.contains(buffer + input.charAt((int)j)))
break;
buffer = buffer + input.charAt((int)j);
j =j +1;
}
output += toBinary(dictionary.indexOf(buffer),wordSize);
if (j<input.length())
dictionary.add(buffer + input.charAt((int)j));
i = j;
}
return output;
}
public String decompress(String inputStr)
{
String decompressStr = "";
List<String> dict = new ArrayList<String>();
dict.add("#");
for(int i=0;i<=255;i++)
dict.add(String.valueOf((char)(i)));
int inputSize = (int)Math.ceil(Math.log(dict.size())/Math.log(2));
int j=0,index=0;
String output1="",output2="",output="",binary="";
while(j < inputStr.length())
{
binary = inputStr.substring(j, j + inputSize);
index = BinaryToDecimal.binaryToDecimal(binary);
output2 = dict.get(index);
output = output + output2;
j = j + inputSize;
if(!dict.contains(output1+output2)){
dict.add(output1+output2);
if(dict.size()>Math.pow(2,inputSize)-1)
inputSize = inputSize + 1;
}
output1 = output2;
}
return decompressStr;
}
}