본문 바로가기

Architecture for Software/Algorithm

RLE(Run-Length Encoding) 알고리즘

나름 Java로 풀어본 RLE 입니다. O(n)이 되도록 신경썼는데~ 잘 풀어진건지 모르겠네요~
고수님들의 많은 의견 부탁드립니다.

참고로 RLE(Run-Length Encoding)는 연속적인 데이터나 문자열 등을 압축하는 알고리즘에 하나입니다. 대표적인 BMP가 이러한 RLE를 사용하여 압축합니다.


/**
 * Copyright (C) 2009, http://www.softwareinlife.com
 *
 * This file is part of "Software in Life".
 *
 * "Vision Software in Life" is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */
package com.softwareinlife.codes;

/**
 * RLE
 * 
 * @author Jang, Sun-Jin (jangsunjin@softwareinlife.com)
 * @date 2009. 11. 9.
 * 
 */
public class RLE {

	/**
	 * Constructor
	 */
	public RLE() {
		super();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		RLE rle = new RLE();
		
		String result = rle.solve("qwwwwwwweeeeerrtyyyyyqqqqwEErTTT");
//		String result = rle.solve("caaab");
		
		System.out.println(result);
	}

	/**
	 * Solve the Problem
	 * 
	 * @param seed
	 * @return
	 */
	private String solve(String seed) {
		StringBuffer rle = new StringBuffer();

		int i = 0;
		int j = 1;
		while (i < seed.length()) {
			char current = seed.charAt(i);
			char after = seed.charAt(j);

			if (current == after) {
				j++;

			} else if (j == (i + 1)) {
				rle.append(current);
				
				i++;
				j = i + 1;
				
			} else {
				rle.append(j - i);
				rle.append(current);

				i = j++;
				j = i + 1;
			}
			
			if (j >= seed.length()) {
				if ((j - i) > 1) {
					rle.append(j - i);					
				}
				rle.append(after);
				
				print(i, j, current, after, rle);				
				break;
			}

			print(i, j, current, after, rle);
		}
		
		return rle.toString();
	}

	/**
	 * Print 
	 * 
	 * @param i
	 * @param j
	 * @param current
	 * @param after
	 * @param rle
	 */
	private void print(int i, int j, char current, char after, StringBuffer rle) {
		System.out.print("i: " + i);
		System.out.print("\t");
		System.out.print("j: " + j);
		System.out.print("\t");
		System.out.print("current: " + current);
		System.out.print("\t");
		System.out.print("after: " + after);
		System.out.print("\t");
		System.out.println("rle: " + rle.toString());
	}
}


'Architecture for Software > Algorithm' 카테고리의 다른 글

최대 공약수 구하기  (0) 2009.11.09
Top Coder에 도전하세요!  (4) 2009.01.01
Algorithm 이란  (0) 2008.11.17
The 3n+1 Problem  (3) 2008.11.11
스택(Stack)  (0) 2008.10.08