เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัวเป็นอาร์กิวเมนต์แรกและสอง เรียกว่า str1 และ str2 ฟังก์ชันต้องตรวจสอบว่ามีการรวมสับสตริงใน str2 ที่เมื่อรวมกันแล้วได้ str2 หรือไม่
ด้วย "การรวมสับสตริง" หมายถึง เราสามารถข้ามตัวอักษรได้ แต่ต้องรักษาลำดับของตัวอักษรที่เลือกจาก str1
ตัวอย่าง
ถ้าสตริงนำเข้าคือ:
const str1 = 'desxooajmepwele'; const str2 = 'example';
ผลลัพธ์ควรเป็น:
const output = true;
เพราะสตริง 'example' สร้างได้จากการเลือกตัวอักษรบางส่วนและรักษาลำดับจาก str1
ตัวอย่างโค้ด
const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsString = (str1 = '', str2 = '') => {
let [foundAt, next] = [0, 0];
for(const char of str2) {
next = str1.slice(foundAt).indexOf(char);
if (next === -1) {
return false;
}
foundAt += next + 1;
}
return true;
};
console.log(containsString(str1, str2));
ผลลัพธ์
true