algorighm/dynamic-programming/subsequence/1143最长公共子序列.js

31 lines
788 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
const longestCommonSubsequence = function (text1, text2) {
};
/*
定义dp[i][j]为text1从i位置开始统计text2从j位置开始统计的最长公共子序列长度如果text1[i]和text2[j]相等则dp[i][j]=dp[i+1][j+1]
若不相等则dp[i][j] = max(dp[i+1][j], dp[i][j+1])
*/
function f1(text1, text2) {
const m = text1.length;
const n = text2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (text1[i] === text2[j]) {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
}
return dp[0][0];
}