最长公共子序列 - 动态规划 二维数组 dpdp, dp[i][j]dp[i][j] 表示 s1s1 前 ii 个字符和 s2s2 前 jj 个字符中最长公共子序列。我们逐行填充 dpdp 数组。
public class Solution {
public int minDistance(String s1, String s2) {
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
if (i == 0 || j == 0)
continue;
if (s1.charAt(i - 1) == s2.charAt(j - 1))
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
return s1.length() + s2.length() - 2 * dp[s1.length()][s2.length()];
}
}
|