1006. 单词变换

来源:互联网 发布:泳道图制作软件 编辑:程序博客网 时间:2024/04/28 05:28


Time Limit: 1sec    Memory Limit:256MB
Description
对于两个只含有小写英文字母(’a’-‘z’)的单词word1和word2,你可以对word1进行以下3种操作:
 
1) 插入一个字母;
2) 删除一个字母;
3) 替换一个字母.
 
请计算将word1变换成word2的最少操作数.
 
word1和word2的长度均不大于1000.
 
请为下面的Solution类实现解决上述问题的函数minDistance,函数的参数word1和word2为给出的两个单词,返回值为所求最少操作数.
 
class Solution {
public:
    int minDistance(string word1, string word2) {
       
       }
};
 
例1:word1 = “sunny”, word2 = “snowy”,返回值为3.
 
例2:word1 = “abc”, word2 = “ac”,返回值为1.

题解:动态规划

class Solution {public:    int minDistance(string word1, string word2) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int row = word1.length() + 1;        int col = word2.length() + 1;                vector<vector<int> > f(row, vector<int>(col));        for (int i = 0; i < row; i++)            f[i][0] = i;        for (int i = 0; i < col; i++)            f[0][i] = i;        for (int i = 1; i < row; i++)            for (int j = 1; j < col; j++){                if (word1[i-1] == word2[j-1])                    f[i][j] = f[i-1][j-1];                else                    f[i][j] = f[i-1][j-1] + 1;                f[i][j] = min(f[i][j], min(f[i-1][j]+1, f[i][j-1]+1));            }        return f[row-1][col-1];    }};

原创粉丝点击