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

时间:2021-05-19

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

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章