2 回答

TA贡献1911条经验 获得超7个赞
不要将整个事情读入内存。处理遇到的代码。读取足够的位以解码下一个代码,对其进行解码,为后续代码保留未使用的位,重复。
不要使用字符串来表示位,每个字符代表一位。使用位来表示位。shift, and, and or 运算符是您应该使用的。您将有一个整数作为位缓冲区,其中包含解码下一个代码所需的所有位。
不要搜索所有代码长度,而是在其中线性搜索所有代码以找到您的代码!我很难想出一个更慢的方法。您应该使用树下降或表查找进行解码。如果您首先生成规范的霍夫曼代码,则可以实现一种简单的查找方法。有关示例,请参见puff.c。教科书的方法(比 puff.c 做的要慢)是在接收端构建相同的 Huffman 树,然后一点一点地沿着树向下直到你得到一个符号。发出符号并重复。
您应该能够在现代处理器的单个内核上在几毫秒内处理 200K 的压缩输入。

TA贡献1963条经验 获得超6个赞
您可以替换字符串concatination+=用StringBuilder。这会分配更少的对象并减少垃圾收集器的负载。
int c;
StringBuilder bitString = new StringBuilder();
//read each byte from file, reverse it, add to giant bitString
//reads ALL BYTES
while ((c = fin.read()) != -1) {
byte current = (byte) c;
StringBuilder currentBitString = new StringBuilder();
for (int q = 0; q < 8; q++) {
byte bits = getBit(current, q);
currentBitString.append(bits);
}
bitString.append(currentBitString.reverse());
}
而不是将代码和数据放入数组中,nodes您应该在HashMap此处使用 a 。您通过迭代整个数组来比较代码,直到找到正确的匹配项。平均而言,这是n/2对String#equals()每个项目的调用。使用 aHashMap您将其减少到〜1。
使用代码作为键的数据填充您的地图。
Map<String, Integer> nodes = new HashMap<>();
nodes.put(code, data);
从地图访问数据
boolean foundCode = false;
for (int j = 0; j < bitString.length(); j++) {
currentBitString.append(bitString.charAt(j));
Integer data = nodes.get(currentBitString.toString().trim());
if (data != null) {
fw.write(data);
foundCode = true;
}
if (foundCode) {
currentBitString = new StringBuilder();
foundCode = false;
}
}
添加回答
举报