프로그래머스 2) [1차] 뉴스 클러스터링

유병수·2023년 5월 2일
0

[1차] 뉴스 클러스터링
카카오 문제는 레벨 2라도 엄청 어려웠다. 언뜻 보면 간단한 문제 같지만 조건이 생각보다 까다로웠다. 파이썬이라면 쉽게 풀었을꺼 같기도 하지만 java는 역시... 그래도 자바로 풀게되면서 정규식이라던가 set문법 등 다양한걸 좀더 공부하게 되었다. 특히 교집합과 합집합에 쓰이는 addAll 과 retainAll도 처음 사용해보았다.

import java.util.*;

class Solution {
    public int solution(String str1, String str2) {
        int answer = 0;
        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();
        
        String[] str1Split = str1.split("");
        String[] str2Split = str2.split("");
        
        ArrayList<String> firstMap = new ArrayList<>();
        ArrayList<String> secondMap = new ArrayList<>();
        
        for(int i=0;i<str1Split.length-1;i++){
            
            String first = str1Split[i];
            String second = str1Split[i+1];
            String check = "[^a-z]";
            
             if(!first.matches(check) && !second.matches(check)){
                 firstMap.add(first + second);    
            }else{
                 System.out.println(first + second);
             }
        }
        
        for(int i=0;i<str2Split.length-1;i++){
            String first = str2Split[i];
            String second = str2Split[i+1];
            String check = "[^a-z]";
            if(!first.matches(check) && !second.matches(check)){
                secondMap.add(first + second);    
            }else{
                System.out.println(str2Split[i] + str2Split[i+1]);
            }
        }
        
        HashSet<String> hash = new HashSet<String>(firstMap);
        hash.retainAll(secondMap);
        int sameCount = 0;
        int maxValue = 0;
        double value = 0.0;
        
        
        Iterator iter = hash.iterator();
        
        if(hash.size() != 0){
             while(iter.hasNext()){
                String str = String.valueOf(iter.next());
                int firstCount = Collections.frequency(firstMap,str);
                int secondCount = Collections.frequency(secondMap,str);
                sameCount += Math.min(firstCount,secondCount);
                maxValue += Math.max(firstCount,secondCount);
            }
            
             ArrayList<String> totalArray = new ArrayList<String>();
            totalArray.addAll(firstMap);    
            totalArray.addAll(secondMap);
            
              int totalCount = totalArray.size() - sameCount ;
                value = (double) sameCount / totalCount;
        }
       
        else if(firstMap.size() == 0 && secondMap.size() == 0){
            value = 1.0;
        }
        else{
            value = 0.0;
        }
        
        answer = (int) (Math.floor(value * 65536));
        
        return answer;
    }
}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN