【发布时间】:2019-11-02 13:12:39
【问题描述】:
我试图计算模式作为字符串的子序列出现的次数,并保留匹配发生的索引。
使用递归调用很容易计数。
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]]
我想将“本地索引”重置为之前的分叉。
我的方向是否正确,或者这类问题是否需要完全不同的实现?
【问题讨论】:
标签: javascript recursion dynamic-programming lcs