240125 문자열 압축

Jongleee·2024년 1월 25일
0

TIL

목록 보기
478/737
public int solution(String s) {
	int answer = s.length();

	for (int i = 1; i <= s.length() / 2; i++) {
		int zipLevel = 1;
		StringBuilder result = new StringBuilder();
		String zipStr = s.substring(0, i);

		for (int j = i; j <= s.length(); j += i) {
			String next = (j + i > s.length()) ? s.substring(j) : s.substring(j, j + i);

			if (zipStr.equals(next)) {
				zipLevel++;
			} else {
				appendCompressed(result, zipLevel, zipStr);
				zipStr = next;
				zipLevel = 1;
			}
		}

		appendCompressed(result, zipLevel, zipStr);
		answer = Math.min(answer, result.length());
	}

	return answer;
}

private void appendCompressed(StringBuilder result, int zipLevel, String zipStr) {
	result.append((zipLevel > 1) ? Integer.toString(zipLevel) : "").append(zipStr);
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/60057

0개의 댓글