欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用游长编码对字符串压缩 Run Length编码示例

程序员文章站 2024-02-20 12:42:58
例:helloooooo => he2l6o 复制代码 代码如下:/** * run-length编码(游长编码) * @author will...

例:helloooooo => he2l6o

复制代码 代码如下:

/**
 * run-length编码(游长编码)
 * @author will
 *
 */
public class runlengthencoder {

 public static void main(string[] args) {  
  string input = "0";

  system.out.println("original string length: " + input.length());

  string encodedstr = encode(input);
  system.out.println("encoded string: " + encodedstr);
  system.out.println("encoded string length: " + encodedstr.length());

  string decodedstr = decode(encodedstr);
  system.out.println("decoded string: " + decodedstr);
 }

 /**
  * 用run-length算法编码字符串
  * @param sourcestr 原始字符串
  * @return
  */
 public static string encode(string sourcestr) {
  if(sourcestr == null || sourcestr.length() <= 1) {
   return sourcestr;
  }

  int len = sourcestr.length();
  stringbuilder resultbuilder = new stringbuilder();
  for(int i = 0; i < len; i++) {
   char cur = sourcestr.charat(i);
   int runlength = 1;
   while((i+1) < len && sourcestr.charat(i+1) == cur) {
    i++;
    runlength++;
   }

   if(runlength > 1) {
    resultbuilder.append(runlength + "" + cur);
   }
   else {
    resultbuilder.append(cur);
   }
  }

  return resultbuilder.tostring();
 }

 /**
  * 解码run-length编码的字符串
  * @param encodedstr
  * @return
  */
 public static string decode(string encodedstr) {
  if(encodedstr == null || encodedstr.length() <= 1) {
   return encodedstr;
  }

  int len = encodedstr.length();
  stringbuilder resultbuilder = new stringbuilder();
  for(int i = 0; i < len; i++) {
   char curchar = encodedstr.charat(i);
   if(character.isdigit(curchar)) {
    i++;
    char nextchar = encodedstr.charat(i);
    int runlength = integer.parseint(curchar + "");
    for(int j = 0; j < runlength; j++) {
     resultbuilder.append(nextchar);
    }
   }
   else {
    resultbuilder.append(curchar);
   }
  }

  return resultbuilder.tostring();
 }

}