✔️ 문제 설명
데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문자열에서 같은 값이 연속해서 나타나는 것을 그 문자의 개수와 반복되는 값으로 표현하여 더 짧은 문자열로 줄여서 표현하는 알고리즘을 공부하고 있습니다.
간단한 예로 "aabbaccc"의 경우 "2a2ba3c"(문자가 반복되지 않아 한번만 나타난 경우 1은 생략함)와 같이 표현할 수 있는데, 이러한 방식은 반복되는 문자가 적은 경우 압축률이 낮다는 단점이 있습니다. 예를 들면, "abcabcdede"와 같은 문자열은 전혀 압축되지 않습니다. "어피치"는 이러한 단점을 해결하기 위해 문자열을 1개 이상의 단위로 잘라서 압축하여 더 짧은 문자열로 표현할 수 있는지 방법을 찾아보려고 합니다.
예를 들어, "ababcdcdababcdcd"의 경우 문자를 1개 단위로 자르면 전혀 압축되지 않지만, 2개 단위로 잘라서 압축한다면 "2ab2cd2ab2cd"로 표현할 수 있습니다. 다른 방법으로 8개 단위로 잘라서 압축한다면 "2ababcdcd"로 표현할 수 있으며, 이때가 가장 짧게 압축하여 표현할 수 있는 방법입니다.
다른 예로, "abcabcdede"와 같은 경우, 문자를 2개 단위로 잘라서 압축하면 "abcabc2de"가 되지만, 3개 단위로 자른다면 "2abcdede"가 되어 3개 단위가 가장 짧은 압축 방법이 됩니다. 이때 3개 단위로 자르고 마지막에 남는 문자열은 그대로 붙여주면 됩니다.
압축할 문자열 s가 매개변수로 주어질 때, 위에 설명한 방법으로 1개 이상 단위로 문자열을 잘라 압축하여 표현한 문자열 중 가장 짧은 것의 길이를 return 하도록 solution 함수를 완성해주세요.
✔️ 제한 사항
- s의 길이는 1 이상 1,000 이하입니다.
- s는 알파벳 소문자로만 이루어져 있습니다.
✔️ 코드 구상
solution에선 문자 개수 단위를 문자열전체길이/2 부터 1까지 바꿔가며 compressing()과 dividing()을 거친 후 제일 짧은 길이를 찾는다.
dividing에선 단위만큼 문자열을 잘라 List에 추가한다.
compressing에선 dividing된 List를 받아 압축한 후 길이를 구한다.
✔️ 1차 코드 (실패)
import java.util.*;
public class Solution {
public int solution(String s) {
int answer = compressing(dividing(s, s.length() / 2));
for(int unit = (s.length() / 2) - 1; unit >= 1; unit--) {
int length = compressing(dividing(s, unit));
if(answer > length) {
answer = length;
}
}
return answer;
}
public List<String> dividing(String s, int unit) {
List<String> list = new ArrayList<>();
int header = 0;
while(header < s.length()) {
if((header + unit) >= s.length()) {
list.add(s.substring(header));
break;
}
list.add(s.substring(header, (header + unit)));
header += unit;
}
return list;
}
public int compressing(List<String> list) {
Set<String> countSet = new HashSet<>();
String header = list.get(0);
for(int i = 1; i < list.size(); i++) {
if(header.equals(list.get(i))) {
countSet.add(list.get(i));
list.remove(i--);
} else {
header = list.get(i);
}
}
int compressedLength = list.stream().mapToInt(e -> e.length()).sum();
int duplicatedCount = countSet.size();
return compressedLength + duplicatedCount;
}
}
✔️ 2차 코드 (실패)
- solution에서 ceil을 사용해 length가 홀수인 경우 커버
- compressing에서 Map 형태로 압축된 결과를 저장해 10번 이상 중복된 경우 글자수 안 맞는 경우 커버
import java.util.*;
public class Solution {
public int solution(String s) {
int answer = s.length();
for(int unit = (int) Math.ceil(s.length() / (float) 2); unit >= 1; unit--) {
int length = compressing(dividing(s, unit));
if(answer > length) {
answer = length;
}
}
return answer;
}
public List<String> dividing(String s, int unit) {
List<String> list = new ArrayList<>();
int header = 0;
while(header < s.length()) {
if((header + unit) >= s.length()) {
list.add(s.substring(header));
break;
}
list.add(s.substring(header, (header + unit)));
header += unit;
}
return list;
}
public int compressing(List<String> list) {
Map<String, Integer> countMap = new HashMap<>();
String header = list.get(0);
for(int i = 1; i < list.size(); i++) {
if(header.equals(list.get(i))) {
if (countMap.containsKey(list.get(i))) {
countMap.put(list.get(i), countMap.get(list.get(i)) + 1);
} else {
countMap.put(list.get(i), 2);
}
list.remove(i--);
} else {
header = list.get(i);
}
}
int compressedLength = list.stream().mapToInt(e -> e.length()).sum();
int duplicatedCount = 0;
for(int value : countMap.values()) {
duplicatedCount += value >= 10 ? 2 : 1;
}
return compressedLength + duplicatedCount;
}
}
✔️ 3차 코드 (성공)
- compressing에서 key를 인덱스로 관리해 떨어져 있는 중복 문자를 Map에서 카운트를 같이하는 경우 커버
import java.util.*;
public class Solution {
public int solution(String s) {
int answer = s.length();
for(int unit = (int) Math.ceil(s.length() / (float) 2); unit >= 1; unit--) {
int length = compressing(dividing(s, unit));
if(answer > length) {
answer = length;
}
}
return answer;
}
public List<String> dividing(String s, int unit) {
List<String> list = new ArrayList<>();
int header = 0;
while(header < s.length()) {
if((header + unit) >= s.length()) {
list.add(s.substring(header));
break;
}
list.add(s.substring(header, (header + unit)));
header += unit;
}
return list;
}
public int compressing(List<String> list) {
Map<Integer, Integer> countMap = new HashMap<>();
String header = list.get(0);
for(int i = 1; i < list.size(); i++) {
if(header.equals(list.get(i))) {
if (countMap.containsKey(i)) {
countMap.put(i, countMap.get(i) + 1);
} else {
countMap.put(i, 2);
}
list.remove(i--);
} else {
header = list.get(i);
}
}
int compressedLength = list.stream().mapToInt(e -> e.length()).sum();
int duplicatedCount = 0;
for(int value : countMap.values()) {
duplicatedCount += value >= 10 ? 2 : 1;
}
return compressedLength + duplicatedCount;
}
}
📄 원문
'🧠 Algorithm > [JAVA] Programmers' 카테고리의 다른 글
[42888번] 오픈채팅방 (0) | 2022.06.18 |
---|---|
[87390번] n^2 배열 자르기 (0) | 2022.06.17 |
[12917번] 문자열 내림차순으로 배치하기 (0) | 2022.06.16 |
[12915번] 문자열 내 마음대로 정렬하기 (0) | 2022.06.15 |
[12910번] 나누어 떨어지는 숫자 배열 (0) | 2022.06.14 |