getOrDefault 함수를 해결하여 프로그래머스 의상 문제 해결

Halo·2025년 6월 21일
0

Algorithm

목록 보기
65/85
post-thumbnail

🔍 Problem

프로그래머스 의상


📃 Input&Output


🌁 문제 배경

가. 문제 설명
각 의상 타입별로 입을지 말지를 선택한 다음 모든 경우의 수를 구하는 문제였다.

두번째 인덱스 값이 의상 타입이다.

나. 접근 방법
첫번째 인덱스 값인 의상이름은 사실 신경 쓸 필요 없고 두번째 의상 인덱스값의 카운트만 HashMap으로 옷 입을지 말지 유무의 모든 경우의 수를 구하면 된다.


📒 수도 코드

가. 먼저 HashMap을 사용하여 각 의상 타입 cnt를 구한다.

HashMap<String, Integer> hm = new HashMap<>();

for (String[] clothe : clothes){
    hm.put(clothe[1],hm.getOrDefault(clothe[1],0)+1);
}

GetOrDefault함수를 사용하여 HashMap 초기화

나. 각 의상별로 안 입는 수를 고려하여 각 cnt+=1을 해주고 모두 곱해준다.

for(Map.Entry<String, Integer> entry : hm.entrySet()){
    //System.out.println(entry.getValue());
    answer*=(entry.getValue()+1);
}

다. 하나도 안 입는 수를 고려하여 각 -1을 해준다.

return answer-1;

💻 Code

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        Scanner sc = new Scanner(System.in);
        int answer = 1;
        HashMap<String, Integer> hm = new HashMap<>();
        
        for (String[] clothe : clothes){
            hm.put(clothe[1],hm.getOrDefault(clothe[1],0)+1);
        }
        
        for(Map.Entry<String, Integer> entry : hm.entrySet()){
            //System.out.println(entry.getValue());
            answer*=(entry.getValue()+1);
        }
    
        
        
        
        return answer-1;
    }
}

🤔 느낀점

자바에는 편리한 라이브러리 함수가 많은 것 같다.

profile
새끼 고양이 키우고 싶다

0개의 댓글