[英]Decoding a bitString using Huffman code table Java
目的是使用霍夫曼代碼表將bitString轉換為純文本,
r=000
h=001
o=01
w=100
d=1010
e=1011
l=11
我將霍夫曼代碼表存儲在兩個不同的String[]
數組中:
String[] ch = {"r", "h", "o", "w", "d", "e", "l"};
String[] b = {"000", "001", "01", "100", "1010", "1011", "11"};
根據霍夫曼代碼表,以下bitString等效於字符串“ helloworld”。
String bits = "001101111110110001000111010";
現在,我想遍歷每組位以匹配其對應的字符:
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bits.length(); i++) {
if(bits.substring(0, b[i].length()).equals(b[i])) {
sb.append(ch[i]);
bits = bits.substring(b[i].length());
}
}
這里的問題是,每次找到匹配項時,我都找不到“重置”循環並返回b[0]
因此我可以從頭開始檢查b[i]
。
您需要逐位讀取源數據“ bit”,並每次都檢查它是否現在是有效的霍夫曼代碼。 我建議您使用Map
(而不是數組)(或者您可以建立樹結構並逐步遍歷),否則性能會變得很慢,因為大多數時候您必須遍歷整個數組。
這是使用霍夫曼代碼表的示例:
import java.util.HashMap;
public class HuffmanDecoder {
private static HashMap<String, String> huffMap = new HashMap<>();
static {
huffMap.put("000", "r");
huffMap.put("001", "h");
huffMap.put("01", "o");
huffMap.put("100", "w");
huffMap.put("1010", "d");
huffMap.put("1011", "e");
huffMap.put("11", "l");
}
public final static void main(String[] args) {
char[] bits = "001101111110110001000111010".toCharArray();
StringBuffer result = new StringBuffer();
StringBuffer temp = new StringBuffer();
for (int i = 0; i < bits.length; i++) {
temp.append(bits[i]);
String val = huffMap.get(temp.toString());
if (val == null) {
continue;
}
result.append(val);
temp.setLength(0);
}
System.out.println(result);
}
}
一旦找到有效代碼,就會將相應的解碼值添加到結果緩沖區中,並重置臨時緩沖區。 缺少的是在接收到不會導致有效代碼值的數據時發生一些錯誤處理,但是該實現是實際代碼的依賴,例如,對於SFF數據(傳真圖像),解碼器會繼續讀取直到到達末尾-of-線標記物。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.