LintCode : Edit Distance

Problem description:

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:

  • Insert a character
  • Delete a character
  • Replace a character

Examples:

Given word1 = "mart" and word2 = "karma", return 3.

Solution:

public class Solution {
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    private int[][] dp;
    public int minDistance(String word1, String word2) {
        // write your code here
        int n = word1.length();
        int m = word2.length();
        // dp[i][j]: 把word1的前i个字符串替换为word2的前j个字符串需要的操作次数
        dp = new int[n + 1][m + 1];
        dp[0][0] = 0;
        for (int i = 1; i <= n; i++) {
            // delete a character
            dp[i][0] = dp[i - 1][0] + 1;
        }
        for (int j = 1; j <= m; j++) {
            // add a character
            dp[0][j] = dp[0][j - 1] + 1;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                // 3 kinds of conditions
                // dp[i - 1][j] to dp[i][j], delete word1[i]
                // dp[i][j - 1] to dp[i][j], add word2[j]
                // dp[i - 1][j - 1], replace word1[i] with word2[j], if the same, no bother
                int step1 = dp[i - 1][j] + 1;
                int step2 = dp[i][j - 1] + 1;
                int step3 = dp[i - 1][j - 1] + 1;
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    step3 = dp[i - 1][j - 1];
                }
                dp[i][j] = Math.min(step1, Math.min(step2, step3));
            }
        }
        return dp[n][m];
    }
}
View Code

This is a dynamic programmin solution, dp[i][j] means how many steps do you have to take to convert word1[0:i] to word2[0:j], so for dp[i][j], we only have 3 conditions, insert a character, delete a character or replace a character.

For dp[i - 1][j] to dp[i][j], you just need to delete a character, because we can change word1[0:i-1] to word2[0:j], so we just need to delete word1.charAt(i -1) to get word1[0:i-1], then we can use dp[i - 1][j] steps to get word2[0:j], so dp[i][j] = dp[i - 1][j] + 1.

For dp[i][j-1] to dp[i][j], we just need to add a character, which is word2.charAt(j -1).

For dp[i -1][j -1], if word1.charAt(i-1) equals word2.charAt(j-1), then nothing need to do, else just need to replace.

posted on 2016-05-22 14:02  dingjunnan  阅读(157)  评论(0编辑  收藏  举报

导航