- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/17677
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/[1차] 뉴스 클러스터링
풀이 시간 : 56분
import java.util.*;
class Solution {
public int solution(String str1, String str2) {
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
Map<String, Integer> map1 = getBigrams(str1);
Map<String, Integer> map2 = getBigrams(str2);
if (map1.isEmpty() && map2.isEmpty()) return 65536;
int inter = 0, union = 0;
for (String key : map1.keySet()) {
int count1 = map1.get(key);
int count2 = map2.getOrDefault(key, 0);
inter += Math.min(count1, count2);
union += Math.max(count1, count2);
}
for (String key : map2.keySet()) {
if (!map1.containsKey(key)) {
union += map2.get(key);
}
}
return (int) (inter * 65536.0 / union);
}
private Map<String, Integer> getBigrams(String str) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < str.length() - 1; i++) {
String pair = str.substring(i, i + 2);
if (pair.matches("[A-Z]{2}")) {
map.put(pair, map.getOrDefault(pair, 0) + 1);
}
}
return map;
}
}