我试图计算模式作为字符串的子序列出现的次数,并保留匹配发生的索引。
使用递归调用很容易计数。
function count(str, pattern, strInd, patternInd) {
if (patternInd === 0) {
return 1;
}
if (strInd === 0) {
return 0;
}
if (str.charAt(strInd - 1) === pattern.charAt(patternInd - 1)) {
const count1 = count(str, pattern, strInd - 1, patternInd - 1);
const count2 = count(str, pattern, strInd - 1, patternInd);
return count1 + count2;
} else {
return count(str, pattern, strInd - 1, patternInd);
}
}
为了保持索引,我的逻辑是当模式字符与字符串字符匹配时,将 str 的当前索引推送到递归调用中的“本地索引数组”,并且一旦模式完成,将“本地索引”推送到“全局索引”并为下一个递归路径重置“本地索引”。
重置本地索引是我面临的问题:
function count(str, pattern, strInd, patternInd) {
if (patternInd === 0) {
// when this path ends, add to list the indices found on this path
globalIndices.push(localIndices);
// reset the local indices
localIndices = [];
console.log("found");
return 1;
}
if (strInd === 0) {
return 0;
}
if (str.charAt(strInd - 1) === pattern.charAt(patternInd - 1)) {
localIndices.push(strInd);
const count1 = count(str, pattern, strInd - 1, patternInd - 1);
const count2 = count(str, pattern, strInd - 1, patternInd);
return count1 + count2;
} else {
return count(str, pattern, strInd - 1, patternInd);
}
}
这样它在每次分叉后都会丢失之前的路径信息,因为一旦匹配的子路径被消耗,它就会从 localIndices 中删除,并且 localIndices 在分叉发生后开始跟踪匹配。
因此,例如,str 是“abab”,模式是“ab”,那么我想要 globalIndices = [[4,3], [4,1], [2,1]] 但我会得到 [[4, 3],[1],[2,1]]
我想将“本地索引”重置为之前的分叉。
我是在朝着正确的方向前进,还是这些问题需要完全不同的实现?
jeck猫
相关分类