mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-08 12:35:16 +08:00
Optimized the code
This commit is contained in:
@ -5,27 +5,32 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
function longestCommonSubsequence (x, y, str1, str2, dp) {
|
function longestCommonSubsequence (x, y, str1, str2, dp) {
|
||||||
if (x == -1 || y == -1) return 0;
|
if (x === -1 || y === -1) {
|
||||||
else {
|
return 0
|
||||||
if (dp[x][y] != 0) return dp[x][y];
|
|
||||||
else {
|
|
||||||
if (str1[x] == str2[y]) {
|
|
||||||
return dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp);
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp))
|
if (dp[x][y] !== 0){
|
||||||
|
return dp[x][y]
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (str1[x] === str2[y]) {
|
||||||
|
dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp);
|
||||||
|
return dp[x][y]
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp))
|
||||||
|
return dp[x][y]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function main () {
|
function main () {
|
||||||
const str1 = "ABCDGH"
|
const str1 = 'ABCDGH'
|
||||||
const str2 = "AEDFHR"
|
const str2 = 'AEDFHR'
|
||||||
const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
|
const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
|
||||||
const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
|
const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
|
||||||
console.log(res);
|
console.log(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
main()
|
main()
|
||||||
|
Reference in New Issue
Block a user