Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับสตริงย่อยที่ตรงกันใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str เป็นอาร์กิวเมนต์แรก และอาร์เรย์ของสตริง arr เป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันควรนับและคืนค่าจำนวนของ arr[i] ที่เป็น subsequence ของสตริง 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