编辑代码

function longestCommonSubsequence(s1, s2) {
  const m = s1.length;
  const n = s2.length;

  // 定义状态数组dp,初始化dp[0][0]为0
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));

  // 填表计算dp数组
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (s1[i - 1] === s2[j - 1]) {
        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[m][n];
}