본문 바로가기

PS

뉴스 클러스터링 [프로그래머스]

1) 문제 접근 방법

- str1, str2에서 각각 문자들로 구성된 것만, HashSet(set1, set2)에 저장한다.

- 그 다음에 set1을 순회하면서, set2에 똑같은 것이 있으면, 삭제하면서, 

  intersection와 union에 추가한다.

- 다음은 set2을 순회하면서, 남은 것들을 union에 추가한다

- union의 사이즈가 0인 경우는, 65536을 그대로 반환한다

- union의 사이즈가 0이 아니면, rate를 계산한 후에, 65536을 곱하고, 

  그것의 내림 값을 반환한다. 

import java.util.*; 

class Solution {

    // 2개의 HashSet을 선언한다. 
    public HashSet<String> set1;
    public HashSet<String> set2;
    
    // check 메소드를 통해, 2개의 Character가 둘 다 문자인지 확인한다. 
    public boolean check(String s){
        if('a' <= s.charAt(0) && s.charAt(0) <= 'z' && 'a' <= s.charAt(1) && s.charAt(1) <= 'z'){
            return true;
        }else{
            return false; 
        }
    }
    
    public int solution(String str1, String str2) {
        int answer = 0;
        ArrayList<String> set1 = new ArrayList<>();
        ArrayList<String> set2 = new ArrayList<>(); 
        ArrayList<String> intersection = new ArrayList<>();
        ArrayList<String> union = new ArrayList<>(); 
        
        // str1을 순회하면서, 2개씩 문자열을 끊어주고,
        // 그 다음에 둘 다 문자인 경우에 set1에 추가한다. 
        for(int i=0; i<str1.length()-1; i++){
            String tmp = str1.substring(i, i+2).toLowerCase();
            if(check(tmp)){
                set1.add(tmp);
            }
        }
                
        // str2을 순회하면서, 2개씩 문자열을 끊어주고,
        // 그 다음에 둘 다 문자인 경우에 set2에 추가한다. 
        for(int i=0; i<str2.length()-1; i++){
            String tmp = str2.substring(i, i+2).toLowerCase();
            if(check(tmp)){
                set2.add(tmp);
            }
        }

        // set1을 순회하면서, set2에 같은 것이 있다면, 
        // remove를 하면서 intersection에 해당 str을 추가한다. 
        // 그리고 str을 union에도 더해준다. 
        for(String str: set1){
            if(set2.remove(str)){
                intersection.add(str);
            }
            union.add(str);
        }
        
        // set2를 순회하면서, union에 str들을 담아준다. 
        for(String str: set2){
            union.add(str); 
        }
        
        // union의 사이즈가 0인경우 65536을 반환한다. 
        if(union.size() == 0){
            return 65536;
        }
        
        // rate를 구하기 위해서 union.size()를 intersection.size()로 나눈다.
        // 이 때, 두 값을 double로 변환한다. 
        double rate = (double)(intersection.size()) / (double)(union.size());
        
        // rate에 65536을 곱하고, 소수점 미만의 값을 버려서
        // jakard를 구한다. 
        int jakard = (int)(65536*rate);
        
        // jakard 값을 반환한다. 
        return jakard;
    }
}

'PS' 카테고리의 다른 글

후보키 [프로그래머스]  (1) 2023.06.03
캐시 [프로그래머스]  (0) 2023.06.03
다트 게임 [프로그래머스]  (1) 2023.06.03
실패율 [프로그래머스]  (0) 2023.06.03
오픈채팅방 [프로그래머스]  (0) 2023.06.03