字符串压缩 使用游长编码对字符串压缩 Run Length编码示例
人气:0想了解使用游长编码对字符串压缩 Run Length编码示例的相关内容吗,在本文为您仔细讲解字符串压缩的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:字符串压缩,游长,编码,下面大家一起来学习吧。
例: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();
}
}
加载全部内容