bug解决方案
来源:6-4 关联字符串-代码演示

_玲
2019-03-08
export default (str, words) => {
// 保存结果
let result = []
// 记录数组的长度,做边界条件计算
let num = words.length
// 递归函数体
let range = (r, _arr) => {
if (r.length === num) {
result.push(r)
} else {
_arr.forEach((item, idx) => {
let tmp = [].concat(_arr)
tmp.splice(idx, 1)
range(r.concat(item), tmp)
})
}
}
range([], words)
// 修改输出
const _result = []
result.forEach(item => {
const sub = item.join('')
for (let i = 0, idx; idx !== -1; i++) {
if (str.length - idx - 1 < sub.length) {
return
}
idx = str.indexOf(sub, i)
i = idx + 1
_result.push(idx)
}
})
return _result.filter(item => item !== -1).sort((a, b) => a - b)
}
测试用例:
test('words', () => {
expect(words('barfoothefoobarman', ['foo', 'bar'])).toEqual([0, 9])
})
test('words:2', () => {
expect(words('wordgoodgoodgoodbestword', ['word', 'good', 'best', 'word'])).toEqual([])
})
test('words3', () => {
expect(words('barfootbarfoobarman', ['foo', 'bar'])).toEqual([0, 7, 10])
})
写回答
1回答
-
快乐动起来呀
2019-03-08
请一定要贡献到issue,今天挨个过大家的issue
00
相似问题