๐ฅ Algorithm/Programmers
[ํ๋ก๊ทธ๋๋จธ์ค] (1์ฐจ) ๋ด์ค ํด๋ฌ์คํฐ๋ง (js)
Lennon
2021. 10. 27. 18:23
728x90
๋ฐ์ํ
https://programmers.co.kr/learn/courses/30/lessons/17677?language=javascript
function solution(str1, str2) {
str1 = divideString(str1).map((v) => v.join("").toLowerCase());
str2 = divideString(str2).map((v) => v.join("").toLowerCase());
let denominatorSet = [...new Set([...str1, ...str2])];
let moleculeSet = str1.filter(v => str2.includes(v));
moleculeSet = [...new Set(moleculeSet)];
let molecule = 0;
let denominator = 0;
for(let i = 0; i < denominatorSet.length; i++){
const strOverlap1 = str1.reduce((prev, cur) => prev + (cur===denominatorSet[i]), 0);
const strOverlap2 = str2.reduce((prev, cur) => prev + (cur===denominatorSet[i]), 0);
denominator+= Math.max(strOverlap1, strOverlap2);
}
for(let i = 0; i < moleculeSet.length; i++){
const strOverlap1 = str1.reduce((prev, cur) => prev + (cur===moleculeSet[i]), 0);
const strOverlap2 = str2.reduce((prev, cur) => prev + (cur===moleculeSet[i]), 0);
molecule+= Math.min(strOverlap1, strOverlap2);
}
return denominator===0 ? 65536 : Math.floor((molecule/denominator)*65536)
}
function divideString(str) {
const result = [];
for(let i = 0; i < str.length; i++){
const sliceStr = str.slice(i,i+2);
let matchStr = sliceStr.match(/[A-Z]/gi);
if(matchStr === null) continue;
else if(matchStr.length === 2){
result.push(matchStr);
}
}
return result;
}
matchํจ์๋ฅผ ๋ฐฐ์ด ํ ์ฒ์ ์จ ๋ดค๋ค.
๋ฐฐ์ด ์์์ ๊ฐ์๋ฅผ ์ฐพ๋ ๊ฑฐ์ ์ ์ฉํ๊ฒ ์ฐ์ผ ์ ์์ ๊ฒ ๊ฐ์ divideString ํจ์์ ์์ฑํด๋ดค๋ค.
์ ๊ท์์ ํตํด ์ฝ๋๊ฐ ๊ฐ๊ฒฐํด์ง ์ ์์๋ค.
728x90
๋ฐ์ํ