使用游长编码对字符串压缩 Run Length编码示例
例: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();
}
}