【动态规划】 EditDistance

思路参考: https://www.cnblogs.com/littlepanpc/p/7895810.html

代码参考:https://leetcode.com/problems/edit-distance/discuss/226308/C-Dynammic-programming-solution-Time%3AO(mn)-4ms-Beat-100

 

#define min(x, y) (((x) < (y)) ? (x) : (y))
int minDistance(char* word1, char* word2) {
    int len1 = strlen(word1);
    int len2 = strlen(word2);
    // printf("%d %d", len1, len2);
    int dp[len1+1][len2+1];
    int i;
    for(i = 0; i <= len1; i++){
        for(int j = 0; j <= len2; j++){
            if(i == 0){
                dp[i][j] = j;
                continue;
            }
            if(j == 0) {
                dp[i][j] = i;
                continue;
            }
            if(word1[i-1]== word2[j-1]) dp[i][j] = dp[i-1][j-1];
            else{
                dp[i][j] = 1 + min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
            }
        }
    }
    return dp[len1][len2];
}

 

posted on 2019-03-01 19:34  时间静止之湖  阅读(143)  评论(0编辑  收藏  举报

导航