字符串压缩编码

参考文章:https://www.cnblogs.com/liuzhuqing/p/7480443.html
自己编写的代码:`
package com.company;

public class TestStringToReduce {

    public  static  String StringToReduce(String str){
        StringBuffer result = new StringBuffer();
        char c1 = str.charAt(0);
        int sum = 1;

        for (int i=1;i<str.length();i++){
            char c2 = str.charAt(i);
                if (c2==c1){
                    sum = sum +1;
                    continue;
                }
                result.append(c1).append(sum);
                c1 = c2;
                sum = 1;
            }
          result.append(c1).append(sum);
        return result.toString();
    }

public static void main(String[] args) {

   System.out.println(StringToReduce("aaaabbxvvv"));
}

}
`关于 static修饰符何时使用:不需要NEW时加static,需要new后再调用不加static。

------还有一个输入的字符串不是按顺序的,想了一个办法:再和全部的比较完之后删除这个字符串(没时间写了)
如果有人写出来了,跟我讲一下哈。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
哈夫曼编码是一种用于数据压缩的算法,它通过将出现频率较高的字符用较短的编码表示,从而实现对数据的压缩。下面是使用Python实现哈夫曼编码和解码的示例代码: ```python import heapq from collections import defaultdict # 构建哈夫曼树 def build_huffman_tree(freq): heap = [[weight, [char, ""]] for char, weight in freq.items()] heapq.heapify(heap) while len(heap) > 1: lo = heapq.heappop(heap) hi = heapq.heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) return heap[0] # 生成哈夫曼编码表 def generate_huffman_code(tree): huffman_code = {} for pair in tree[1:]: char = pair[0] code = pair[1] huffman_code[char] = code return huffman_code # 压缩字符串 def compress_string(string, huffman_code): compressed_string = "" for char in string: compressed_string += huffman_code[char] return compressed_string # 解压字符串 def decompress_string(compressed_string, huffman_code): decompressed_string = "" code = "" for bit in compressed_string: code += bit for char, c in huffman_code.items(): if code == c: decompressed_string += char code = "" break return decompressed_string # 示例 string = "hello world" freq = defaultdict(int) for char in string: freq[char] += 1 tree = build_huffman_tree(freq) huffman_code = generate_huffman_code(tree) compressed_string = compress_string(string, huffman_code) decompressed_string = decompress_string(compressed_string, huffman_code) print("原始字符串:", string) print("压缩后的字符串:", compressed_string) print("解压后的字符串:", decompressed_string) ``` 运行以上代码,将输出以下结果: ``` 原始字符串: hello world 压缩后的字符串: 0110111011110010111001100 解压后的字符串: hello world ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值