Don't be afraid of challenges
[프로그래머스 Lv.2] [1차] 뉴스 클러스터링 본문
https://school.programmers.co.kr/learn/courses/30/lessons/17677
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1차 시도
const set = (string)=> {
let arr = [];
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let newStr = string.toUpperCase().split("");
for(let i =0; i<newStr.length-1; i++){
let str = newStr[i]+newStr[i+1];
if(alphabet.includes(newStr[i]) && alphabet.includes(newStr[i+1]))arr.push(str);
}
return arr;
}
function solution(str1, str2) {
let ch_str1 = set(str1);
let ch_str2 = set(str2);
if(ch_str1.length ==0 && ch_str2.length ==0) return 65536;
let totalSet = ch_str1.concat(ch_str2)
let intersection = []; // 교집합
for(let i =0; i<totalSet.length; i++){
let p = totalSet.lastIndexOf(totalSet[i]);
if(p !== i) {
intersection.push(totalSet[p]);
totalSet.splice(p,1);
}
}
return totalSet.length === 0 ? 65536 : parseInt((intersection.length / totalSet.length) * 65536);
}

이렇게 하니까 안됐음 ...
처음에 str1, str2에서 나오는 배열 각각을 다 합쳐서 totalSet을 만들어서 거기서 교집합 합집합을 나눴는데 이게 아닌가 ? 하고 str1 배열 str2 배열을 각각 나눠서 따로따로 비교를 해봤더니 됐다...
그리고 밑에 코드를 좀 더 깔끔하게 정리할 수 있음
_전_
const set = (string)=> {
let arr = [];
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let newStr = string.toUpperCase().split("");
for(let i =0; i<newStr.length-1; i++){
let str = newStr[i]+newStr[i+1];
if(alphabet.includes(newStr[i]) && alphabet.includes(newStr[i+1]))arr.push(str);
}
return arr;
}
_후_
const set = (string)=> {
string = string.toUpperCase();
let newStr = string.split("").map((s,i)=> s+string[i+1]).filter((set)=> set.match(/[A-Z]{2,}/g));
return newStr;
}
2차 시도
const set = (string)=> {
string = string.toUpperCase();
let newStr = string.split("").map((s,i)=> s+string[i+1]).filter((set)=> set.match(/[A-Z]{2,}/g));
return newStr;
}
function solution(str1, str2) {
let ch_str1 = set(str1);
let ch_str2 = set(str2);
if(ch_str1.length ==0 && ch_str2.length ==0) return 65536;
let intersection = [];
for(let i =0; i< ch_str1.length; i++){
let idx = ch_str2.indexOf(ch_str1[i]);
if(idx > -1) intersection.push(ch_str2.splice(idx,1))
}
return parseInt(intersection.length / (ch_str1.length+ch_str2.length) * 65536);
}

'이것이 코딩테스트다' 카테고리의 다른 글
| 투포인터 알고리즘 (0) | 2024.12.19 |
|---|---|
| [알고리즘] 정렬 알고리즘 (1) | 2024.10.18 |
| [프로그래머스- Lv.2] 귤고르기 (1) | 2024.09.14 |
| [프로그래머스] Lv.2 H-Index - js (0) | 2024.05.02 |
| [프로그래머스] Lv.1 푸드 파이트 대회 - js (2) | 2024.04.30 |