เราต้องเขียนฟังก์ชันคืน true หากส่วนหนึ่งของ string1 จัดเรียงใหม่ได้เป็น string2 เขียนฟังก์ชัน scramble(str1,str2) คืน true หากตัวอักษรบางส่วนของ str1 จัดเรียงใหม่ตรง str2 ได้ มิฉะนั้น false
เช่น
string1 คือ str1 และ string2 คือ str2 str1 คือ 'cashwool' และ str2 คือ 'school' ควรคืน true str1 คือ 'katas' และ str2 คือ 'steak' ควรคืน false
โค้ด เราแค่ split และ sort สองสตริง แล้วตรวจสอบว่าสตริงเล็กเป็น substring ของสตริงใหญ่หรือไม่
ตัวอย่าง
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