문제 설명


제한 사항
입출력 예 참고
입출력 예

풀이
import java.util.HashMap;
import java.util.Map;
class Solution {
public int solution(String str1, String str2) {
HashMap<String, Integer> str1Map = new HashMap<>();
HashMap<String, Integer> str2Map = new HashMap<>();
for (int i = 0; i < str1.length() - 1; i++) {
String temp = str1.substring(i, i + 2).toLowerCase();
if (temp.matches("[a-z]+")) {
str1Map.put(temp, str1Map.getOrDefault(temp, 0) + 1);
}
}
for (int i = 0; i < str2.length() - 1; i++) {
String temp = str2.substring(i, i + 2).toLowerCase();
if (temp.matches("[a-z]+")) {
str2Map.put(temp, str2Map.getOrDefault(temp, 0) + 1);
}
}
int inter = 0, union = 0;
for (Map.Entry<String, Integer> entry : str1Map.entrySet()) {
if (str2Map.containsKey(entry.getKey())) {
inter += Math.min(entry.getValue(), str2Map.get(entry.getKey()));
union += Math.max(entry.getValue(), str2Map.get(entry.getKey()));
}
else union += entry.getValue();
}
for (Map.Entry<String, Integer> entry : str2Map.entrySet()) {
if (!str1Map.containsKey(entry.getKey()))
union += entry.getValue();
}
return union == 0 ? 65536 : (int)Math.floor((double)inter / union * 65536);
}
}
후기
문제가 좀 길다...ㅎㅎ 교집합과 합집합을 어떻게 구할지가 문제인데 교집합은 두 Map에서 공통된 key를 가지고 있는 문자열의 value 중에 작은 값을 선택하고, 합집합은 최대로 가질 수 있어야 하니까 큰 값을 선택한다. 그리고 합집합의 경우는 두 Map에서 서로 가지고 있지 않은 요소도 포함시켜야 하므로 그 부분은 따로 처리해서 더해주었다.
'코딩테스트 (프로그래머스) > Java' 카테고리의 다른 글
| [프로그래머스][JAVA][Lv. 4] 도둑질 (0) | 2023.09.16 |
|---|---|
| [프로그래머스][JAVA][Lv. 3] 이중우선순위큐 (0) | 2023.09.15 |
| [프로그래머스][JAVA][Lv. 2] 프로세스 (0) | 2023.09.12 |
| [프로그래머스][JAVA][Lv. 0] 배열 조각하기 (0) | 2023.09.11 |
| [프로그래머스][JAVA][Lv. 2] 기능 개발 (0) | 2023.09.08 |