当前位置: 移动技术网 > IT编程>开发语言>Java > 使用游长编码对字符串压缩 Run Length编码示例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

例: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();
 }

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网