Leetcode 72. Edit Distance

来源:互联网 发布:excel图表数据区域扩大 编辑:程序博客网 时间:2024/06/07 12:25

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

题目大意是: 有两个 字符串, 找到把word1 转化成 word2 最少的操作步骤。

维护一个二维数组 dp[ i ][ j ] , dp[ i ][ j ] 表示 把 word1 [0 .. i - 1]   转换到 word1 [0 .. j - 1] 所需的最小步骤。

例子: word1: abcd   word2: qwer

dp[ 4 ][ 0 ] 表示 把 abcd 转化成 “” 所需 步骤, 所以是 4.

所以

dp[ i ][ 0 ] = i

dp[ 0 ][ j ] = j

如果 word1[ i - 1] 等于word2[ j - 1] ,dp[ i ][ j ] = dp[ i  - 1][ j - 1] ,则不需要做任何改动

If they are not equal, we need to consider three cases:

  1. Replace word1[i - 1] by word2[j - 1] (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement));
  2. Delete word1[i - 1] and word1[0..i - 2] = word2[0..j - 1] (dp[i][j] = dp[i - 1][j] + 1 (for deletion));
  3. Insert word2[j - 1] to word1[0..i - 1] and word1[0..i - 1] + word2[j - 1] = word2[0..j - 1] (dp[i][j] = dp[i][j - 1] + 1 (for insertion)).

替换:把word1[ i - 1]  替换成 word2[ j - 1] 则需要 把 在dp[ i  - 1][ j - 1]的基础上 加 1, 所以是  dp[ i ][ j ] = dp[ i  - 1][ j - 1] + 1

删除:把word1[ i - 1]  删除, 使得word1[ i - 2] 和 word2[ j - 1]  一样, 需要把替换成 word2[ j - 1]  ,  dp[ i ][ j ] = dp[ i  - 1][ j ] + 1

加入:把word2[ j - 1] 加入到word1中, dp[ i ][ j ] = dp[ i ][ j - 1] + 1




    public int minDistance(String word1, String word2) {        int len1 = word1.length(), len2 = word2.length();                int[][] dp = new int[len1 + 1][len2 + 1];                for (int i = 1; i <= len1; i++) {            dp[i][0] = i;        }        for (int j = 1; 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] = Math.min(dp[i][j - 1], Math.min(dp[i - 1][j - 1], dp[i - 1][j])) + 1;            }        }        return dp[len1][len2];    }