เราต้องเขียนฟังก์ชันตรวจสอบว่า str2 สร้างได้จาก str1 โดยการลบตัวอักษรบางส่วนเท่านั้น (ไม่เปลี่ยนลำดับตัวอักษรที่เหลือ)
ตัวอย่าง: str1='sjkfampeflef', str2='sample' → true
ตัวอย่างโค้ด
const str1 = 'sjkfampeflef';
const str2 = 'sample';
const checkConvertibility = (str1 = '', str2 = '') => {
if (!str1 || !str2) { return false; }
const strArr1 = str1.split('');
const strArr2 = str2.split('');
const shorter = strArr1.length < strArr2.length ? strArr1 : strArr2;
const longer = strArr1.length < strArr2.length ? strArr2 : strArr1;
for (let i = 0; i < shorter.length; i++) {
const el = shorter[i];
const index = longer.indexOf(el);
if (index !== -1) { longer.splice(index, 1); continue; }
return false;
}
return true;
};
console.log(checkConvertibility(str1, str2));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
true