leetcode problem notes 72

Given you two words  word1 and  word2return   the minimum number of operations that will be used to word1 convert word2 them   .

You can perform the following three operations on a word:

  • insert a character
  • delete a character
  • replace a character

Idea 1: Dynamic programming

int minDistance(char * word1, char * word2){
    //动态规划
        int dp[501][501];
        int i,j;
        int size1=strlen(word1);
        int size2=strlen(word2);
        dp[0][0]=0;
        for(i=0;i<=size2;i++){
            dp[0][i]=i;
        }
        for(i=0;i<=size1;i++){
            dp[i][0]=i;
        }
        for(i=1;i<=size1;i++){
            for(j=1;j<=size2;j++){
                dp[i][j]=fmin(dp[i-1][j],fmin(dp[i][j-1],dp[i-1][j-1]))+1;
                if(word1[i-1]==word2[j-1]){
                    dp[i][j]=fmin(dp[i][j],dp[i-1][j-1]);
                }
            }
        }
        return dp[size1][size2];
}

Time complexity O(n^2), space complexity O(n)

analyze:

This question changes a string into another string. First, the length needs to be the same, that is, delete one or insert one, and then make the characters in the two strings the same. The operation of deletion and insertion can be converted into dp[i] [j]=fmin(dp[i-1][j],fmin(dp[i][j-1],dp[i-1][j-1]))+1;, the replacement operation is transformed into dp[i][j]=fmin(dp[i][j],dp[i-1][j-1]); finally output dp[size1][size2]

Summarize:

This question examines the problem of dynamic programming, which can be solved by converting the operations of deletion, insertion, and replacement into dynamic programming to compare the size of two grid values

Guess you like

Origin blog.csdn.net/si_mple_/article/details/132253292