在 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
