프로그래머스 - [1차] 뉴스 클러스터링
해당 문제는 입력 받은 문자열들을 문제의 조건에 맞는 집합으로 변경하면서 중복 원소를 허용 하므로 해시로 구현 했습니다.
이후 교집합과 합집합은 문제 설명 그대로 구현하였습니다.
public int solution(String str1, String str2) {
Map<String, Integer> str1Set = getSet(str1);
Map<String, Integer> str2Set = getSet(str2);
if (str1Set.isEmpty() && str2Set.isEmpty()) {
return 1;
}
double intersectionCount = getIntersection(str1Set, str2Set);
double unionCount = getUnionCount(str1Set, str2Set);
double calcu = intersectionCount / unionCount;
return (int) (calcu * 65536);
}
private int getUnionCount(Map<String, Integer> str1Set, Map<String, Integer> str2Set) {
AtomicInteger unionCount = new AtomicInteger();
str1Set.forEach((element, count) -> {
if (str2Set.containsKey(element)) {
unionCount.addAndGet(Math.max(count, str2Set.get(element)));
} else {
unionCount.addAndGet(count);
}
});
str2Set.forEach((element, count) -> {
if (!str1Set.containsKey(element)) {
unionCount.addAndGet(count);
}
});
return unionCount.get();
}
private int getIntersection(Map<String, Integer> str1Set, Map<String, Integer> str2Set) {
AtomicInteger intersectionCount = new AtomicInteger();
str1Set.forEach((element, count) -> {
if (str2Set.containsKey(element)) {
intersectionCount.addAndGet(Math.min(count, str2Set.get(element)));
}
});
return intersectionCount.get();
}
private Map<String, Integer> getSet(String str) {
Map<String, Integer> strSet = new HashMap<>();
for (int i = 0; i < str.length() - 1; i++) {
String element = str.substring(i, i + 2).toUpperCase();
if (element.charAt(0) < 65 || element.charAt(0) > 90 ||
element.charAt(1) < 65 || element.charAt(1) > 90) {
continue;
}
strSet.put(element, strSet.getOrDefault(element, 0) + 1);
}
return strSet;
}
'정리 > 알고리즘' 카테고리의 다른 글
프로그래머스 - 약수의 개수와 덧셈 (0) | 2022.04.19 |
---|---|
프로그래머스 - 소수만들기 (0) | 2022.04.18 |
프로그래머스 - 괄호 변환 (0) | 2022.04.13 |
프로그래머스 - 실패율 (0) | 2022.04.11 |
프로그래머스 - 메뉴 리뉴얼 (0) | 2022.04.08 |
댓글