https://school.programmers.co.kr/learn/courses/30/lessons/17677
package kakaoCodingTest;
import java.util.ArrayList;
public class 뉴스클러스터링 {
public static int solution(String str1, String str2) {
ArrayList<String> strSet1 = sliceSet(str1.toLowerCase());
ArrayList<String> strSet2 = sliceSet(str2.toLowerCase());
int intersection = 0;
int union = strSet1.size() + strSet2.size();
for(int i=0; i<strSet1.size(); i++) {
if(strSet2.contains(strSet1.get(i))) {
strSet2.remove(strSet1.get(i));
intersection++;
}
}
union -= intersection;
if(union == 0 ) {
return 65536;
}else {
return 65536*intersection/union;
}
}
public static ArrayList<String> sliceSet(String str) {
ArrayList<String> res = new ArrayList<>();
for (int i = 0; i < str.length() - 1; i++) {
if(('a' <= str.charAt(i) && str.charAt(i) <= 'z') &&
('a' <= str.charAt(i+1) && str.charAt(i+1) <= 'z')) {
res.add(str.substring(i, i + 2));
}
}
return res;
}
}
자카드 계수를 활용하는 문제이다. 합집합과 교집합의 성질만 알면 금방 풀 수 있는 비교적 간단한 문제이다.
public static ArrayList<String> sliceSet(String str) {
ArrayList<String> res = new ArrayList<>();
for (int i = 0; i < str.length() - 1; i++) {
if(('a' <= str.charAt(i) && str.charAt(i) <= 'z') &&
('a' <= str.charAt(i+1) && str.charAt(i+1) <= 'z')) {
res.add(str.substring(i, i + 2));
}
}
return res;
}
문자열에서 연속된 두 개의 문자가 영어 소문자로만 구성되어있을 경우 슬라이싱하여 String형태로 ArrayList에 저장하여 반환한다.
public static int solution(String str1, String str2) {
ArrayList<String> strSet1 = sliceSet(str1.toLowerCase());
ArrayList<String> strSet2 = sliceSet(str2.toLowerCase());
int intersection = 0;
int union = strSet1.size() + strSet2.size();
for(int i=0; i<strSet1.size(); i++) {
if(strSet2.contains(strSet1.get(i))) {
strSet2.remove(strSet1.get(i));
intersection++;
}
}
union -= intersection;
if(union == 0 ) {
return 65536;
}else {
return 65536*intersection/union;
}
}
소문자로 변환한 입력값을 sliceSet 메서드를 이용하여 ArrayList를 만든다. 초기 교집합의 값은 0이지만, strSet1에서 인덱스를 하나씩 돌면서 strSet2에도 동일한 값이 있으면 strSet2에서 원소를 제거하고 intersection을 +1해주는 식으로 계산한다.
합집합은 초기에는 단순히 두 집합의 크기의 합으로 계산되었지만, 그 값에서 교집합을 빼주고, 출력 형식에 알맞게 결과값에 65536을 곱하여 출력한다.