프로그래머스 뉴스 클러스터링 (Java,자바)

jonghyukLee·2022년 9월 3일
0

이번에 풀어본 문제는
프로그래머스 뉴스 클러스터링 입니다.

📕 문제 링크

❗️코드

import java.util.*;
class Solution {
    public int solution(String str1, String str2) {
        int answer = 0;

        int str1Length = str1.length();
        int str2Length = str2.length();

        String str1Low = str1.toLowerCase();
        String str2Low = str2.toLowerCase();

        Map<String, Integer> map1 = new HashMap<>();
        Map<String, Integer> map2 = new HashMap<>();

        double intersection = 0.0;
        double union = 0.0;

        for (int i = 0; i < str1Length - 1; i++) {
            char fst = str1Low.charAt(i);
            char sec = str1Low.charAt(i + 1);

            if (bothAlpha(fst, sec)) {
                String key = fst + "" + sec;
                map1.put(key,map1.getOrDefault(key, 0) + 1);
            }
        }

        for (int i = 0; i < str2Length - 1; i++) {
            char fst = str2Low.charAt(i);
            char sec = str2Low.charAt(i + 1);

            if (bothAlpha(fst, sec)) {
                String key = fst + "" + sec;
                map2.put(key,map2.getOrDefault(key, 0) + 1);
            }
        }

        if (map1.size() == 0 && map2.size() == 0) return 65536;

        for (String key : map1.keySet()) {
            if (map2.containsKey(key)) {
                intersection += Math.min(map1.get(key), map2.get(key));
                union += Math.max(map1.get(key), map2.get(key));
                map2.remove(key);
            }
            else {
                union += map1.get(key);
            }
        }

        for (String key : map2.keySet()) {
            union += map2.get(key);
        }

        answer = (int)Math.floor((intersection / union) * 65536);

        return answer;
    }
    static boolean bothAlpha(char fst, char sec) {
        return fst >= 97 && sec >= 97 && fst <= 122 && sec <= 122;
    }
}

📝 풀이

문제에 주어진 조건에 따라 교집합 / 합집합을 구하는 문제입니다.
다중집합에 대한 교집합, 합집합은 문제에 주어진대로 min, max로 계산했고 HashMap으로 카운트를 처리했습니다.
주어진 두 문자열이 모두 공집합일 경우만 별도로 체크해주면, 위의 방식으로 해결할 수 있습니다.

📜 후기

다중집합이란 개념을 처음 들어봐서 문제를 이해하는 데 시간이 조금 걸렸습니다.

profile
머무르지 않기!

0개의 댓글