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

}

좋은 웹페이지 즐겨찾기