ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str เป็นอาร์กิวเมนต์แรก และอาร์เรย์ของสตริง arr เป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันของเราควรนับและส่งคืนจำนวน arr[i] ที่สืบเนื่องมาจากสตริง str
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ
ป้อนข้อมูล
const str = 'klmnop'; const arr = ['k', 'll', 'klp', 'klo'];
ผลผลิต
const output = 3;
คำอธิบายผลลัพธ์
เนื่องจากสตริงที่ต้องการคือ 'k', 'klp' และ 'klo'
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'klmnop';
const arr = ['k', 'll', 'klp', 'klo'];
const countSubstrings = (str = '', arr = []) => {
const map = arr.reduce((acc, val, ind) => {
const c = val[0]
acc[c] = acc[c] || []
acc[c].push([ind, 0])
return acc
}, {})
let num = 0
for (let i = 0; i < str.length; i++) {
if (map[str[i]] !== undefined) {
const list = map[str[i]]
map[str[i]] = undefined
list.forEach(([wordIndex, charIndex]) => {
if (charIndex === arr[wordIndex].length - 1) {
num += 1
} else {
const nextChar = arr[wordIndex][charIndex + 1]
map[nextChar] = map[nextChar] || []
map[nextChar].push([wordIndex, charIndex + 1])
}
})
}
}
return num
}
console.log(countSubstrings(str, arr)); ผลลัพธ์
3