
내 코드 :
function solution(X, Y) {
let answer = '';
const countX = Array(10).fill(0);
const countY = Array(10).fill(0);
for (let char of X) {
countX[char]++;
}
for (let char of Y) {
countY[char]++;
}
for (let i = 9; i >= 0; i--) {
const commonCount = Math.min(countX[i], countY[i]);
if (commonCount > 0) {
answer += i.toString().repeat(commonCount);
}
}
if (answer === '') return "-1";
if (answer[0] === "0") return "0";
return answer;
}
const countX = Array(10).fill(0);
const countY = Array(10).fill(0);
배열의 10칸을 0으로 채우는 코드이다.
for (let char of X) {
countX[char]++;
}
for (let char of Y) {
countY[char]++;
}
X, Y 문자열로 반복문을 돌려서 countX와 coutY 배열의 각 char 인덱스에 1을 더한다. (문자형도 인덱스로 쓸 수 있었다.)
for (let i = 9; i >= 0; i--) {
const commonCount = Math.min(countX[i], countY[i]);
if (commonCount > 0) {
answer += i.toString().repeat(commonCount);
}
}
출력값이 내림차순이어야 하므로 X와 Y의 9인덱스부터 인덱스 0까지 반복문을 돌며 commonCount가 0 초과이면(X와 Y에 둘다 값이 하나 이상 있으면) answer에 i를 commomCount 수만큼 반복하여 붙인다.