72. Edit Distance && 161. One Edit Distance

Posted 蜃利的阴影下

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了72. Edit Distance && 161. One Edit Distance相关的知识,希望对你有一定的参考价值。

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

 
Classic DP problem. DP feels like mathematical induction
 
/**
 * dp[r][c] indicates the minimum number of operations to convert word1[0,r] to word2[0,c]
 * boundary conditions:
 * dp[r][0] = r
 * dp[0][c] = c
 * <p>
 * if word1[r] == word2[c]:  dp[r][c] = dp[r-1][c-1]
 * else:  dp[r][c] = min(dp[r-1][c-1]+1, dp[r-1][c]+1, dp[r][c-1]+1)
 * <p>
 * dp[r-1][c-1]+1 means "replace the last character of word1 with the last character of word2"
 * dp[r-1][c]+1 means "delete the last character from word1":
 *    dp[r-1][c] already matches. The extra word1[r] is useless, so we remove it
 * dp[r][c-1]+1 means "add the last character of word2 to the end of word1":
 *    dp[r][c-1] already matches. In order to match word2[c], we need to add it to the end of word1
 */
class Solution {
  public int minDistance(String word1, String word2) {
    int ROW = word1.length();
    int COL = word2.length();
    int[][] dp = new int[ROW + 1][COL + 1];
    for (int r = 1; r <= ROW; ++r)
      dp[r][0] = r;
    for (int c = 1; c <= COL; ++c)
      dp[0][c] = c;

    for (int r = 1; r <= ROW; ++r) {
      for (int c = 1; c <= COL; ++c) {
        if (word1.charAt(r - 1) == word2.charAt(c - 1))
          dp[r][c] = dp[r - 1][c - 1];
        else
          dp[r][c] = Math.min(dp[r - 1][c - 1] + 1, Math.min(dp[r][c - 1] + 1, dp[r - 1][c] + 1));
      }
    }
    return dp[ROW][COL];
  }
}

 

161. One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

 

 

 

 

以上是关于72. Edit Distance && 161. One Edit Distance的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode72 Edit Distance

72. Edit Distance

72. Edit Distance

72. Edit Distance

Leetcode 72. Edit Distance

算法: 编辑距离使得单词相同 72. Edit Distance