應用游長編碼對字符串緊縮 Run Length編碼示例。本站提示廣大學習愛好者:(應用游長編碼對字符串緊縮 Run Length編碼示例)文章只能為提供參考,不一定能成為您想要的結果。以下是應用游長編碼對字符串緊縮 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();
}
}