diff --git a/javascript/1143-Longest-Common-Subsequence.js b/javascript/1143-Longest-Common-Subsequence.js index 756db3824..04bd19884 100644 --- a/javascript/1143-Longest-Common-Subsequence.js +++ b/javascript/1143-Longest-Common-Subsequence.js @@ -1,17 +1,16 @@ var longestCommonSubsequence = function (text1, text2) { - let m = text1.length; - let n = text2.length; + let m = text1.length, + n = text2.length, + DP = new Array(m + 1).fill(0).map(_ => new Array(n + 1).fill(0)); - let table = new Array(m + 1).fill().map(() => new Array(n + 1).fill(0)); - - for (let i = 1; i <= m; i++) { - for (let j = 1; j <= n; j++) { - if (text1.charAt(i - 1) !== text2.charAt(j - 1)) { - table[i][j] = Math.max(table[i - 1][j], table[i][j - 1]); + for (let x = m - 1; x >= 0; x--) + for (let y = n - 1; y >= 0; y--) { + if (text1[x] === text2[y]) { + DP[x][y] = 1 + DP[x + 1][y + 1]; } else { - table[i][j] = table[i - 1][j - 1] + 1; + DP[x][y] = Math.max(DP[x + 1][y], DP[x][y + 1]); } } - } - return table[m][n]; -}; \ No newline at end of file + + return DP[0][0]; +};
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: