72 Edit Distance

ref: 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

分析&代码

ref: Leetcode Discuss

如果用dp[i][j]表示word1里[0,i]长的子串和word2[0,j]的最小编辑距离,那么状态转移方程应该这样构成:

dp[i][j] = dp[i-1][j-1], if word1[i] == word2[j]

dp[i][j] = max{dp[i-1][j], dp[i][j-1], dp[i-1][j-1]} + 1, otherwise
如果word1[i] == word2[j]的时候不需要解释,

如果不相等的时候可能有三种操作,使两个字符串对齐:

  • 替换字母:把word1[i] 替换成word2[j],那么是dp[i-1][j-1]+1
  • 在Word1[i]后面强行插入一个word2[j]. 所以可能是dp[i][j-1]
  • 直接把word1[i]删了,dp[i-1][j]

所以用二维矩阵表示很容易:

public int minDistance(String word1, String word2) {
    int len1 = word1.length();
    int len2 = word2.length();

    //distance[i][j] is the distance converse word1(1~ith) to word2(1~jth)
    int[][] distance = new int[len1 + 1][len2 + 1]; 
    for (int j = 0; j <= len2; j++)
        {distance[0][j] = j;} //delete all characters in word2
    for (int i = 0; i <= len1; i++)
        {distance[i][0] = i;}

    for (int i = 1; i <= len1; i++) {
        for (int j = 1; j <= len2; j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) { //ith & jth
                distance[i][j] = distance[i - 1][j - 1];
            } else {
                distance[i][j] = Math.min(Math.min(distance[i][j - 1], distance[i - 1][j]), distance[i - 1][j - 1]) + 1;
            }
        }
    }
    return distance[len1][len2];        
}

但是,可以像uniquePath一样把二维压成一维

pre表示上同一行前一列的值,f[j-1]表示f[i-1][j-1](因为pre没有更新进去),f[j]表示同一列上一行

public int minDistance(String word1, String word2) {
    if(word1 == null || word2 == null) {
        return -1;
    }
    int len1 = word1.length();
    int len2 = word2.length();
    int[] distance = new int[len2 + 1];
    for(int i = 0; i <= len2; i++) {
        distance[i] = i;
    }
    for(int i = 1; i <= len1; i++) {
        int pre = i;
        for(int j = 1; j <= len2; j++) {
            int cur = 0;
            if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
                cur = distance[j - 1];
            } else {
                cur = Math.min(pre, Math.min(distance[j], distance[j - 1])) + 1;
            }
            distance[j - 1] = pre;
            pre = cur;
        }
        distance[len2] = pre;
    }
    return distance[len2];
}

results matching ""

    No results matching ""