[JAVA 문제 풀이] 302. 의상

프로그래머스 (42578)
Stupefyee's avatar
Jun 05, 2025
[JAVA 문제 풀이] 302. 의상
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public int solution(String[][] clothes) { int answer = 1; Map<String, Integer> clothingCount = new HashMap<>(); // 옷 종류별 개수 저장 // 각 옷 종류 개수 세기 for (String[] cloth : clothes) { clothingCount.put(cloth[1], clothingCount.getOrDefault(cloth[1], 0) + 1); } // 경우의 수를 구하는 조합론 규칙 >> 경우의 수 + 1의 전체 곱에서 1을 빼기 for (Map.Entry<String, Integer> entry : clothingCount.entrySet()) { answer *= entry.getValue() + 1; } return answer - 1; } }
 

다른 사람의 코드

import java.util.*; import static java.util.stream.Collectors.*; class Solution { public int solution(String[][] clothes) { return Arrays.stream(clothes) // 2차원 배열 clothes를 스트림으로 변환 .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting()))) // 옷 종류별로 그룹화하고, 각 종류의 옷 개수를 센다 .values() // 각 종류의 옷 개수만 추출 (예: [2, 1, 3]) .stream() // 옷 개수 스트림으로 변환 .collect(reducing(1L, (x, y) -> x * (y + 1))) // 각 종류별 (개수+1)를 모두 곱함 (입지 않는 경우 포함) .intValue() - 1; // 아무것도 안 입는 경우(모두 미착용)를 빼줌 } }
 
Share article

stupefyee