LeetCode[72] Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

DP

复杂度
O(MN), O(MN)

思路
考虑用二维dp来表示变换的情况。
如果两个字符串中的字符相等,a[i] = b[j],那么dp[i][j] = dp[i - 1][j - 1] + 1;
如果两个字符串中的字符不相等,那么考虑不同的情况

insert: dp[i][j] = dp[i][j - 1] + 1;
replace: dp[i][j] = dp[i - 1][j - 1] + 1;
delete: dp[i][j] = dp[i - 1][j] + 1;
dp[i][j]表示的是,从字符串1到i的位置转换到字符串2到j的位置,所需要的最少步数。

代码

public int minDistance(String word1, String word2) {
    int len1 = word1.length();
    int len2 = word2.length();
    int[][] dp = new int[len1 + 1][len2 + 1];
    // initialize the dp array;
    for(int i = 0; i < len1; i ++) {
        dp[i + 1][0] = i + 1;
    }
    for(int j = 0; j < len2; j ++) {
        dp[0][j + 1] = j + 1;
    }
    //
    char[] arr1 = word1.toCharArray();
    char[] arr2 = word2.toCharArray();
    for(int i = 0; i < len1; i ++) {
        for(int j = 0; j < len2; j ++) {
            if(arr1[i] == arr2[j]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            }
            else {
                dp[i][j] = Math.min(dp[i - 1][j - 1], 
                    Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
            }
        }
    }
    return dp[len1][len2];
}

hellolittleJ17
10 声望11 粉丝