LeetCode 72. Edit Distance

Description

https://leetcode.com/problems/edit-distance/
给定两个单词word1和word2,找到将word1转换为word2所需的最小操作次数。每次允许的操作:插入、删除、修改一个字母

Solving Ideas

https://www.youtube.com/watch?v=We3YDTzNXEk

动态规划:

State:
dp[i][j]: 表示word1.substring(0, i)转成word2.substring(0, j)所需要的最小操作次数。

如:word1 = “abc”,word2 = “de”
dp[1][1] = 1 表示将"a"转成"d"所需要的最小操作次数为1

Initial State:

  • dp[i][0] = i
  • dp[0][j] = j

State Transition:

  • if (word1[i - 1] == word2[j - 1]) dp[i][j] = dp[i - 1][j - 1];
  • else dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);

时间复杂度: O ( m ∗ n ) O(m*n) O(mn)
空间复杂度: O ( m ∗ n ) O(m*n) O(mn)

Solution

class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return -1;
        }

        int len1 = word1.length(), len2 = word2.length();
        if (len1 == 0 || len2 == 0) {
            return len1 + len2;
        }

        int[][] dp = new int[len1 + 1][len2 + 1];
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j - 1],
                            Math.min(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }

        return dp[len1][len2];
    }
}

你可能感兴趣的:(Leetcode,LeetCode)