在 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 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练