java字符串压缩算法代码
时间: 2023-11-12 18:28:50 浏览: 93
以下是Java中几种字符串压缩算法的示例代码:
RLE算法:
```java
public static String compressRLE(String str) {
StringBuilder result = new StringBuilder();
int count = 1;
char prev = str.charAt(0);
for (int i = 1; i < str.length(); i++) {
char current = str.charAt(i);
if (current == prev) {
count++;
} else {
result.append(count).append(prev);
count = 1;
prev = current;
}
}
result.append(count).append(prev);
return result.toString();
}
```
LZW算法:
```java
public static String compressLZW(String str) {
Map<String, Integer> dictionary = new HashMap<>();
for (int i = 0; i < 256; i++) {
dictionary.put("" + (char) i, i);
}
String current = "";
List<Integer> codes = new ArrayList<>();
for (char c : str.toCharArray()) {
String next = current + c;
if (dictionary.containsKey(next)) {
current = next;
} else {
codes.add(dictionary.get(current));
dictionary.put(next, dictionary.size());
current = "" + c;
}
}
if (!current.equals("")) {
codes.add(dictionary.get(current));
}
StringBuilder result = new StringBuilder();
for (int code : codes) {
result.append(code).append(" ");
}
return result.toString();
}
```
Huffman编码算法:
```java
public static String compressHuffman(String str) {
Map<Character, Integer> frequencies = new HashMap<>();
for (char c : str.toCharArray()) {
frequencies.put(c, frequencies.getOrDefault(c, 0) + 1);
}
PriorityQueue<Node> queue = new PriorityQueue<>();
for (Map.Entry<Character, Integer> entry : frequencies.entrySet()) {
queue.offer(new Node(entry.getKey(), entry.getValue()));
}
while (queue.size() > 1) {
Node left = queue.poll();
Node right = queue.poll();
Node parent = new Node('\0', left.frequency + right.frequency, left, right);
queue.offer(parent);
}
Map<Character, String> codes = new HashMap<>();
buildCodes(codes, queue.peek(), "");
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
result.append(codes.get(c));
}
return result.toString();
}
private static void buildCodes(Map<Character, String> codes, Node node, String code) {
if (node.left == null && node.right == null) {
codes.put(node.character, code);
} else {
buildCodes(codes, node.left, code + "0");
buildCodes(codes, node.right, code + "1");
}
}
private static class Node implements Comparable<Node> {
char character;
int frequency;
Node left;
Node right;
Node(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
Node(char character, int frequency, Node left, Node right) {
this.character = character;
this.frequency = frequency;
this.left = left;
this.right = right;
}
@Override
public int compareTo(Node o) {
return frequency - o.frequency;
}
}
```
以上代码仅供参考,实际使用时可能需要根据具体需求进行修改和优化。
阅读全文