문제 링크
문제 요약
풀이 흐름
counts.put(type, colunts.get(type) == null ? 0 : counts.get(type) + 1);
// key에 해당하는 value가 null이라면 default 값을 사용하라.
-> counts.put(type, colunts.getOrDefault(type, 0) + 1);
코드
풀이 언어 : JAVA
public int solution(String[][] clothes) {
Map<Integer, List<String>> map = new HashMap<>();
for(int i=0;i<clothes.length;++i) {
List<String> clothes_list;
int hash = clothes[i][1].hashCode();
if(map.containsKey(hash))
clothes_list = map.get(hash);
else
clothes_list = new ArrayList<>();
clothes_list.add(clothes[i][0]);
map.put(hash, clothes_list);
}
int answer = 1;
Set<Integer> keySet = map.keySet();
for(int key : keySet ) {
answer *= map.get(key).size() + 1;
}
answer-=1;
return answer;
}
해설 풀이
public int solution(String[][] clothes) {
Map<String, Integer> counts = new HashMap<>();
for(String[] c : clothes) {
String type = c[1];
counts.put(type, colunts.getOrDefault(type, 0) + 1);
}
int answer = 1;
for(Integer c : counts.values()) {
answer *= c + 1;
}
answer -= 1;
}
그리고 이걸 더 간결하게 줄이면 아래 코드
public int solution(String[][] clothes) {
Map<String, Integer> counts = new HashMap<>();
// 각 type은 여러개가 나올 수 있으니 중복을 제거(distinct) 하여 type값을 얻을 수 있다.
// 특정 타입의 옷만 보겠다고 한다면
// 전체 옷을 stream을 사용해서 filter로 첫번째 요소가 type과 같은지 보고
// 그 count를 구하여 type에 대한 갯수를 구할 수 있다.
// count()는 long으로 리턴되니까 int로 형변환 필요
// 그리고 count 값에 1을 더해서 사용
int answer= Arrays.stream(clothes)
.map(c -> c[1])
.distinct()
.map(type -> (int) Arrays.stream(clothes).filter(c -> c[1].equals(type)).count())
.map(c -> c + 1)
.reduce(1, (c, n) -> c * n);
return answer - 1;
}