我需要编写一个函数,其中给定一组字符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.length 时,最终会给出错误的结果(因为你没有考虑跳过 str 中的某些字符并且将字符串后面的字符与键匹配)。
关于javascript - 如何递归地查找字符串中的一组字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383031/