문자열1(str1)의 일부 문자들을 재배열하여 문자열2(str2)와 동일하게 만들 수 있는지 판별하는 함수를 작성해 보겠습니다.
즉, scramble(str1, str2) 함수는 str1에 포함된 일부 문자들을 재배열하여 str2를 만들 수 있으면 true를, 만들 수 없으면 false를 반환합니다.
예시
str1이 'cashwool'이고 str2가 'school'인 경우 → true
str1이 'katas'이고 str2가 'steak'인 경우 → false
'cashwool'에는 'school'을 만드는 데 필요한 모든 문자(c, s, h, o×2, l)가 포함되어 있으므로 true가 되고, 반면 'katas'에는 'steak'에 필요한 t와 e가 없기 때문에 false가 됩니다.
해결 접근 방식
핵심 아이디어는 매우 간단합니다. 두 문자열을 각각 한 글자씩 분리(split)한 뒤 알파벳순으로 정렬(sort)하고 다시 하나의 문자열로 합칩니다(join). 그다음, 길이가 짧은 문자열이 긴 문자열 안에 포함되어 있는지 확인하면 됩니다. 포함되어 있다면 필요한 문자들이 모두 존재한다는 의미이므로 true를 반환합니다.
예제 코드
const str1 = 'cashwool';
const str2 = 'school';
const scramble = (str1, str2) => {
const { length: len1 } = str1;
const { length: len2 } = str2;
const firstSortedString = str1.split("").sort().join("");
const secondSortedString = str2.split("").sort().join("");
if(len1 > len2){
return firstSortedString.includes(secondSortedString);
}
return secondSortedString.includes(firstSortedString);
};
console.log(scramble(str1, str2));
실행 결과
콘솔에 출력되는 결과는 다음과 같습니다.
true
코드 설명
split(""): 문자열을 개별 문자 배열로 분리합니다.sort(): 배열의 문자들을 알파벳순으로 정렬합니다.join(""): 정렬된 문자들을 다시 하나의 문자열로 결합합니다.includes(): 특정 문자열이 다른 문자열에 포함되어 있는지 확인하여 true 또는 false를 반환합니다.