알고리즘/프로그래머스
[프로그래머스] [자바] [카카오] 튜플
글을 쓰는 개발자
2021. 12. 17. 09:08
반응형
https://programmers.co.kr/learn/courses/30/lessons/64065
코딩테스트 연습 - 튜플
"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]
programmers.co.kr
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public int[] solution(String s) {
Tuple tuple = new Tuple(s);
return tuple.mappingCountToChunks().getValue();
}
public static class Tuple {
private final String[] chunk;
private int maxSize = 0;
private final Map<Integer,Set<Integer>> map;
public Tuple(String s) {
s = s.replace("{{", "");
s = s.replace("}}", "");
this.chunk = s.split("[}][,][{]");
this.map = new HashMap<>();
}
public Tuple mappingCountToChunks() {
for (String ch : chunk) {
String[] parts = ch.split(",");
Set<String> set = new HashSet<>(List.of(parts));
Set<Integer> v =set.stream().map(Integer::valueOf).collect(Collectors.toSet());
map.put(parts.length,v);
maxSize = Math.max(maxSize,parts.length);
}
return this;
}
public int[] getValue() {
int[] answer = new int[maxSize];
for (int i=maxSize;i>=1;i--) {
Set<Integer> right = map.get(i);
Set<Integer> left = map.get(i-1);
if (left != null)
right.removeAll(left);
answer[i-1] = right.iterator().next();
}
return answer;
}
}
}
이 문제에서 제가 생각한 핵심 자료형은 Set 이었습니다. 그 이유는 현 위치와 바로 그 전의 위치에서의 차집합을 구하면 우리가 원하는 값을 찾을 수 있기 때문입니다.


여기에서 A를 {2,1,3,4}라고 하고 B를 {2,1,3}이라고 하겠습니다.
이때 A-B를 하면 {4}가 나오는데 이 때 4번째 위치 값이 4인 것을 알 수가 있습니다.
그러면 이제 풀이에서 나온 메서드 들에 대하여 설명해보겠습니다.
Tuple
생성자로서 주어진 문자열에 대해서 파싱을 하고 그에 대한 결과 값을 chunk 에 넣는 작업을 진행합니다.
mappingCountToChunks
파싱한 문자열을 크기에 따라 Map 자료형에 넣는 작업을 해줍니다.
getValue
값을 구하는 메서드로서 제일 큰 Set부터 시작하여 작은 순으로 시작합니다.
이 때 주의해야 할 점은 마지막에는 left 가 null이기 때문에 removeAll을 하면 에러가 난다는 것에 유의해야 합니다.
반응형