第十周:[leetCode] 72. Edit Distance

来源:互联网 发布:苹果电脑ai软件 编辑:程序博客网 时间:2024/06/07 02:58

题目:链接

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

为加强利用动态规划解题的思维,我时不时会选择一道动态规划的题目进行学习,在写之前搜到一篇解析很详细且清楚的文章,那我就以简单明了的方式说明:

解题思路:    新建二维数组,D[len1+1][len2+2]保存编辑距离的长度,其中D[i][j] 为 word1 的0-i位组成的子串和word2的0-j位组成的子串的编辑距离,则有:(1) word1或word2其中一个长度为0,则编辑距离为另一字符串长度。    D[i][0] = i;       D[0][j] = j;(2)状态转移方程:                  1. D[i-1][j] + 1;    D[i][j] =     2. D[i][j-1] + 1;                  3. D[i-1][j-1] + inc;    1 & 2. D[i-1][j]、D[i-1][j-1]进行增删换操作(即+1),可以得到 D[i][j] 3. 如果word1第i位与word2第j位相等,不用进行增删换,inc为0,否则同上为1

c++解题:

    int minDistance(string word1, string word2) {        int len1 = word1.size();        int len2 = word2.size();        int D[len1+1][len2+1];        //设置初始状态        for(int i = 0; i <= len2; i++)            D[0][i] = i;        for(int i = 0; i <= len1; i++)            D[i][0] = i;        for(int c = 1; c <= len2; c++){            for(int r = 1; r <= len1; r++){                int m = min(D[r-1][c], D[r][c-1]);                //word2的第c位为word2[c-1],同word1,易错点                int inc = word2[c-1] == word1[r-1]?0:1;                D[r][c] = min(m + 1, D[r-1][c-1] + inc);            }        }        return D[len1][len2];    }
0 0
原创粉丝点击