Skip to content

Instantly share code, notes, and snippets.

@devetude
Created November 1, 2017 03:45
Show Gist options
  • Save devetude/7ba73e01eac96b0624f6938f40b1cda9 to your computer and use it in GitHub Desktop.
Save devetude/7ba73e01eac96b0624f6938f40b1cda9 to your computer and use it in GitHub Desktop.
Run Length Encoding
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Run Length Encoding
*
* @author devetude
*/
public class Main {
// RLE 구분자 문자 상수
private static final char PREFIX = '+';
/**
* 메인 메소드
*
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception {
// 버퍼를 통해 입력 값을 받음
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
br.close();
int strLen = str.length();
if (strLen > 0) {
char beforeChar = str.charAt(0);
int cnt = 1;
// 버퍼를 통해 결과 값을 만듬
StringBuilder sb = new StringBuilder();
for (int i = 1; i < strLen; i++) {
char currentChar;
if ((currentChar = str.charAt(i)) == beforeChar) {
cnt++;
} else {
if (cnt > 1) {
if (sb.length() > 0) {
sb.append(PREFIX);
}
sb.append(cnt).append(beforeChar);
cnt = 1;
} else {
sb.append(beforeChar);
}
beforeChar = currentChar;
}
}
if (cnt > 1) {
sb.append(PREFIX).append(cnt).append(beforeChar);
} else {
sb.append(beforeChar);
}
// 결과 값을 한꺼번에 출력
System.out.print(sb.toString());
} else {
System.out.print("Length of input string is 0.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment