LeetCode 72 questions: edit distance (difficult)

LeetCode 72 questions: edit distance (difficult)

  • Title: Given two words word1 and word2, word1 to calculate the minimum number of converting operations word2 used. You can perform the following three operations on one word: insert a character, delete a character, replace a character

  • A thought: ① start thinking a bit compared, to operate. But the idea is very simple examples can be cited unreasonable. ② then later want to search about the location of each letter, and select the appropriate location, where no other place to settle down is the need for action. However, several letters may exist, there may be no need to insert. and so. . . I think I will not. . . .

  • Ideas II: Interpretations are given in the idea of ​​dynamic programming, with dp [i] [j] represents a bit before i became word1 word2 number of steps before the j bits needed. When the last one is the same, dp [i] [j] = dp [i-1] [j-1]; when the last one is not the same, dp [i] [j] = min (dp [i-1] [ j-1], dp [i-1] [j], dp [i] [j-1]) + 1. Wherein, dp [i-1] [j-1] represents a replacement operation, dp [i-1] [j] indicates deletion, dp [i] [j-1] represent insertion operation. In addition, consider the case of a word is empty.

class Solution {
    public int minDistance(String word1, String word2) {
        int n1 = word1.length();
        int n2 = word2.length();
        int[][] dp = new int[n1 + 1][n2 + 1];
        // 第一行
        for (int j = 1; j <= n2; j++) dp[0][j] = dp[0][j - 1] + 1;
        // 第一列
        for (int i = 1; i <= n1; i++) dp[i][0] = dp[i - 1][0] + 1;

        for (int i = 1; i <= n1; i++) {
            for (int j = 1; j <= n2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1];
                else dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1;
            }
        }
        return dp[n1][n2];  
    }
}

Here Insert Picture Description

Published 79 original articles · won praise 7 · views 1367

Guess you like

Origin blog.csdn.net/new_whiter/article/details/104477562