在 JavaScript 中计算匹配的子字符串
问题
我们需要编写一个JavaScript函数,它接受一个字符串str作为第一个参数,一个字符串数组arr作为第二个参数。我们的函数应该计算并返回字符串str的子序列arr[i]的数量。
例如,如果函数的输入是
输入
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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下