删除字符 两串相等

  1. Input: "sea", "eat"
  2. Output: 2
  3. Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

可以转换为求两个字符串的最长公共子序列问题。

  1. public int minDistance(String word1, String word2) {
  2. int m = word1.length(), n = word2.length();
  3. int[][] dp = new int[m + 1][n + 1];
  4. for (int i = 1; i <= m; i++) {
  5. for (int j = 1; j <= n; j++) {
  6. if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
  7. dp[i][j] = dp[i - 1][j - 1] + 1;
  8. } else {
  9. dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
  10. }
  11. }
  12. }
  13. return m + n - 2 * dp[m][n];
  14. }