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.

 

public class Solution {
  public boolean isOneEditDistance(String s, String t) {
    int l1 = s.length();
    int l2 = t.length();
    if (l1 == l2)
      return isOnlyOneCharDifferent(s, t);
    if (l1 - l2 == 1)
      return isOneCharInsertion(s, t);
    if (l2 - l1 == 1)
      return isOneCharInsertion(t, s);
    return false;
  }

  private boolean isOnlyOneCharDifferent(String s, String t) {
    boolean modified = false;
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) != t.charAt(i)) {
        if (modified) return false;
        modified = true;
      }
    }
    return modified;
  }

  //find the first character that doesn't equal and then compare the rest of the string
  private boolean isOneCharInsertion(String longString, String shortString) {
    for (int i = 0; i < shortString.length(); ++i) {
      if (longString.charAt(i) != shortString.charAt(i)) {
        return longString.substring(i + 1).equals(shortString.substring(i));
      }
    }
    return true;
  }
}

 

 

 

 
posted @ 2016-09-01 06:00  新一代的天皇巨星  阅读(173)  评论(0)    收藏  举报