[프로그래머스 Level1] 신고 결과 받기 (Java11)

안대현·2022년 6월 28일
0

프로그래머스 Level1 : 신고 결과 받기

프로그래머스 Level1에 새로 추가된 문제가 3개 있어서, 오늘은 신고 결과 받기 문제를 풀이하였다. 특별히 어렵진 않았고, HashMap 자료구조를 사용하여 풀이하였다.

구현 코드

import java.util.HashMap;
import java.util.StringTokenizer;

public class ReportResult {
    public int[] solution(String[] id_list, String[] report, int k) {
        int[] answer = new int[id_list.length];

        HashMap<String, Integer> countMap = new HashMap<>(id_list.length);  // 신고 횟수를 저장하기 위한 HashMap
        HashMap<String, Integer> reportMap = new HashMap<>();   // "유저ID 신고한ID"를 저장하기 위한 HashMap

        for (String r : report) {
            StringTokenizer st = new StringTokenizer(r);
            st.nextToken();
            String reported = st.nextToken();   // 유저가 신고한 ID

            /** 현재 반복문의 report 배열의 원소 r이 reportMap에 없으면 0을, 있으면 키에 해당하는 값을 반환받는다.
             *  ex) 현재 r이 "muzi frodo"일 때, reportMap의 key에 "muzi frodo"가 있으면
             *      해당 키의 value를 가져오고, 없으면 defaultValue로 지정한 0을 가져온다.
             *      만일, 가져온 값이 0이면 muzi가 frodo를 처음 신고한 것이므로,
             *      countMap에서 frodo를 찾아 value에 1을 더해준 뒤, reportMap에 (r,1)을 추가한다. **/
            int re = reportMap.getOrDefault(r, 0);

            if (re == 0) {
                countMap.put(reported, countMap.getOrDefault(reported, 0) + 1);
                reportMap.put(r, 1);
            }
        }

        // reportMap의 keySet으로 반복문을 실행한다.
        for (String s : reportMap.keySet()) {
            StringTokenizer st = new StringTokenizer(s);
            String reporter = st.nextToken();   // 유저 ID
            String reported = st.nextToken();   // 유저가 신고한 ID

            for (int i = 0; i < id_list.length; i++) {
                String name = id_list[i];

                // name이 유저ID와 일치하면 해당 유저가 신고한 ID가 정지된 아이디인지 확인하고,
                // 정지된 아이디면 answer[i]를 1만큼 증가시킨다.
                if (reporter.equals(name)) {
                    if (countMap.getOrDefault(reported, 0) >= k) {
                        answer[i] += 1;
                    }
                }
            }
        }

        return answer;
    }
}
profile
백엔드 개발자로 향하는 계단을 오르고 있습니다! 😎

0개의 댓글