javascript最不常见的子序列,实现缓存
我正在尝试实现“”问题的javascript版本。我正在关注java实现: 如何以Java解决方案中的方式实现阵列 编辑: 它似乎适用于某些输入,例如字符串1:“abcde”字符串2:“ace” 但在其他情况下失败,例如字符串1:“pmjghexybyrgzczy”字符串2:“hafcdqbgncrcbihkd”javascript最不常见的子序列,实现缓存,javascript,arrays,multidimensional-array,Javascript,Arrays,Multidimensional Array,我正在尝试实现“”问题的javascript版本。我正在关注java实现: 如何以Java解决方案中的方式实现阵列 编辑: 它似乎适用于某些输入,例如字符串1:“abcde”字符串2:“ace” 但在其他情况下失败,例如字符串1:“pmjghexybyrgzczy”字符串2:“hafcdqbgncrcbihkd” 感谢您的帮助。问题在于阵列初始化时使用的大小是相反的。我不知道Java版本是否真的能正常工作,但是如果s1和s2的长度相同,或者s2更长,您的Javascript就能正常工作。如果s1
感谢您的帮助。问题在于阵列初始化时使用的大小是相反的。我不知道Java版本是否真的能正常工作,但是如果
s1
和s2
的长度相同,或者s2
更长,您的Javascript就能正常工作。如果s1
比s2
长,它将崩溃,因为它试图在您创建的边界之外建立索引
解决方案是更改初始化,使行数组基于s2
的长度,列基于s1
的长度。当您的缓存大小为[4][5]时,您的缓存超出了范围并引用了缓存[5][0]
(例如)
工作代码:
var longestCommonSubsequence=函数(s1,s2){
让缓存=[];
设max=0;
//***初始化缓存***
对于(设i=0;我请包括传递给longestCommonSubsequence
)的值。它对我有效。str1:“pmjghexybyrgzczy”str2:“hafcdqbgnccbihkd”更新了问题@Mordred,thanks@Mordred我明白了。在我的第一个循环中,我为(设i=0;i它仍将在其他输入上中断。现在编写解决方案。
// working solution
class BottomUp {
public int longestCommonsubsequenceLength(String s1, String s2) {
int cache[][] = new int[s2.length() + 1][s1.length() + 1];
for (int s2Row = 0; s2Row <= s2.length(); s2Row++) {
for (int s1Col = 0; s1Col <= s1.length(); s1Col++) {
if (s2Row == 0 || s1Col == 0) {
cache[s2Row][s1Col] = 0;
} else if (s2.charAt(s2Row - 1) == s1.charAt(s1Col - 1)) {
cache[s2Row][s1Col] = cache[s2Row - 1][s1Col - 1] + 1;
}
else {
cache[s2Row][s1Col] = Math.max(cache[s2Row - 1][s1Col], cache[s2Row][s1Col - 1]);
}
}
}
return cache[s2.length()][s1.length()];
}
}
var longestCommonSubsequence = function(s1, s2) {
let cache = [];
let max = 0;
// ***initialize cache***
for(let i = 0; i <= s1.length; i++) {
cache.push(new Array(s2.length + 1).fill(0));
}
for (let s2Row = 0; s2Row <= s2.length; s2Row++) {
for (let s1Col = 0; s1Col <= s1.length; s1Col++) {
if (s2Row == 0 || s1Col == 0) {
cache[s2Row][s1Col] = 0; // crashes here. 'Cannot set property '0' of undefined
} else if (s2.charAt(s2Row - 1) == s1.charAt(s1Col - 1)) {
cache[s2Row][s1Col] = cache[s2Row - 1][s1Col - 1] + 1;
}
else {
cache[s2Row][s1Col] = Math.max(cache[s2Row - 1][s1Col], cache[s2Row][s1Col - 1]);
}
}
}
return cache[s2.length][s1.length];
};