【LeetCode】72. Edit Distance

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

 

递归超时。

又是一个“走地图”的动态规划算法。

word1, word2只有两个字符串,因此可以展平为一个二维地图,转换代价即从左上角走到右下角的最小代价。

记代价矩阵为dist. dis[i][j]代表word1[0,i)转换为word2[0,j)的最小代价。

当word1到达第i-1个元素,word2到达第j-1个元素:

地图上往右一步代表word1当前位置插入了word2[j-1]字符,dis[i][j]=dis[i][j-1]+1, 下一次比较word1[i-1]和word2[j]

地图上往下一步代表word1当前位置删除了word1[i-1]字符,dis[i][j]=dis[i-1][j]+1, 下一次比较word1[i]和word2[j-1]

地图上往对角线一步代表word1[i-1]替换为word2[j-1](相同则不替换),dis[i][j]=dis[i-1][j-1]+((word1[i-1]==word2[j-1])?0:1),下一次比较word1[i]和word2[j]

示例:word1="a", word2="ab"

dis  0    a    b

0    0    1    2

a    1    0    1

 

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        vector<vector<int> > dis(m+1, vector<int>(n+1, 0));
        for(int i = 1; i <= n; i ++)
            dis[0][i] = i;
        for(int i = 1; i <= m; i ++)
            dis[i][0] = i;
        for(int i = 1; i <= m; i ++)
        {
            for(int j = 1; j <= n; j ++)
            {
                int carry;
                if(word1[i-1] == word2[j-1])
                    carry = 0;
                else
                    carry = 1;
                dis[i][j] = min(dis[i-1][j-1]+carry, min(dis[i-1][j]+1, dis[i][j-1]+1));
            }
        }
        return dis[m][n];
    }
};

posted @ 2014-12-09 15:51  陆草纯  阅读(205)  评论(0编辑  收藏  举报