源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-05-30 09:39 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:使用游长编码对字符串压缩 Run Length编码示例
例:Helloooooo => He2l6o
[u]复制代码[/u] 代码如下:
/**  * 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();  } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部