如何递归地查找字符串中的一组字符

How to recursively find a set of a characters in a string?

本文关键字:一组 字符 查找 何递归 递归 字符串      更新时间:2023-09-26

我需要编写一个函数,在给定一组字符key的情况下,找到字符串str中出现的唯一实例的数量,这样

findKeys("fooo","foo") //returns 3
//foo-
//fo-o
//f-oo
findKeys("foobarfoo","obo") //returns 4]
//--ob----o 
//-o-b---o-
//-o-b----o
//--ob---o-

以下是我到目前为止的函数,我不知道我缺少了什么,但我只知道它没有找到所有的实例,所以它没有正确地遍历字符串。

function findKeys(str, key) {
  var count = count || 0;
  if(str.length <= key.length || key.length === 1) {
    if(str.slice(0, key.length) === key) {
      return 1
    }
    return 0
  }
  if(str[0] === key[0]) {
    count += findKeys(str.slice(1), key.slice(1))
  }
  count += findKeys(str.slice(1), key)
  return count
}

只需删除

|| key.length === 1

从您的功能。我不知道为什么你在里面有这个-当key.length是1但str.length大于key.lengh时,最终会给出错误的结果(因为你没有考虑跳过str中的一些字符并将字符串的后面字符与key匹配的情况)。