[programmers][X] [1차] 뉴스 클러스터링

https://school.programmers.co.kr/learn/courses/30/lessons/17677

(gCnt / sCnt) * 65536

이 식에서 gCnt와 sCnt는 둘 다 정수이기 때문에 gCnt / sCnt는 정수 나눗셈이 일어나고, 소수점 이하가 버려딘다.

예: gCnt = 1, sCnt = 2일 때 gCnt / sCnt = 0 (정수 나눗셈) → 0 * 65536 = 0 이 되어버린다.

double로 바꿔주는거 주의하자.

import java.util.*;

class Solution {
    public int solution(String str1, String str2) {
        int answer = 0;

        Map<String,Integer> m1 = new HashMap<>();
        Map<String,Integer> m2 = new HashMap<>();

        for(int i = 1 ; i < str1.length() ; i++){
            String temp = str1.substring(i-1,i+1);
            temp = temp.toUpperCase();
            if(temp.matches("[A-Z]+")) m1.put(temp, m1.getOrDefault(temp,0)+1);
        }

        for(int i = 1 ; i < str2.length() ; i++){
            String temp = str2.substring(i-1,i+1);
            temp = temp.toUpperCase();
            if(temp.matches("[A-Z]+")) m2.put(temp, m2.getOrDefault(temp,0)+1);
        }

        int gCnt = 0;
        int sCnt = 0;

        for(String key1 : m1.keySet()){
            int m1no = m1.get(key1);
            int m2no = m2.getOrDefault(key1,0);

            gCnt += Math.min(m1no,m2no);
            sCnt += Math.max(m1no,m2no);
        }

        for(String key2 : m2.keySet()){
            if(!m1.containsKey(key2)) sCnt += m2.get(key2);
        }

        if(gCnt == 0 && sCnt == 0){
            return 65536;
        }

        return (int) Math.floor( ((double) gCnt/sCnt) *65536);
    }
}

© 2023 Lee. All rights reserved.