
내가 작성한 코드
class Solution {
public int solution(String s) {
int answer = s.length(); // 압축 길이의 최소값 초기화
// 문자열을 자를 단위 길이 >> 1부터 s.length()/2 까지 시도
for (int i = 1; i <= s.length() / 2; i++) {
StringBuilder compressed = new StringBuilder(); // 압축 문자열 저장
String prev = s.substring(0, i); // 첫 단위 문자열
int count = 1; // 같은 문자열 반복 횟수
// i 단위로 자르면서 비교
for (int j = i; j <= s.length(); j += i) {
// 다음 단위 문자열
String curr = (j + i <= s.length()) ? s.substring(j, j + i) : s.substring(j);
if (prev.equals(curr)) {
count++; // 같은 문자열 반복
} else {
// 압축 문자열 생성
if (count > 1) {
compressed.append(count); // 반복 개수
}
compressed.append(prev); // 이전 문자열
// 초기화
prev = curr;
count = 1;
}
}
// 마지막에 남은 문자열 처리
if (count > 1) {
compressed.append(count);
}
compressed.append(prev);
// 최소 길이 갱신
answer = Math.min(answer, compressed.length());
}
return answer;
}
}
다른 사람의 코드
class Solution {
public int solution(String s) {
int answer = s.length();
// 1 ~ s.length()/2 개 단위로 압축
for (int i = 1; i <= s.length() / 2; i++) {
int result = getSplitedLength(s, i, 1).length();
answer = i == 1 ? result : (answer > result ? result : answer);
}
return answer;
}
// n개 단위로 압축한 문자열을 반환하는 재귀 함수
public String getSplitedLength(String s, int n, int repeat) {
if (s.length() < n)
return s;
String result = "";
String preString = s.substring(0, n);
String postString = s.substring(n, s.length());
// 불일치 -> 현재까지 [반복횟수 + 반복문자] 조합
if (!postString.startsWith(preString)) {
if (repeat == 1)
return result += preString + getSplitedLength(postString, n, 1);
return result += Integer.toString(repeat) + preString + getSplitedLength(postString, n, 1);
}
return result += getSplitedLength(postString, n, repeat + 1);
}
}
Share article