leetcode 72. Edit Distance

来源:互联网 发布:网络传播推广方案 编辑:程序博客网 时间:2024/05/18 02:33

72. 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

这种题就是动态规划来做!f[i][j]代表word1的前i位变成word2的前j位需要多少步骤。

class Solution {public:    int minDistance(string word1, string word2)     {        int row = word1.size();        int col = word2.size();           int f[row + 1][col + 1] = {0};        for (int i = 0; i <= row; i++)        {            for (int j = 0; j <= col; j++)            {                if (i == 0)                    f[i][j] = j;                else if (j == 0)                    f[i][j] = i;                else                {                    if (word1[i - 1] == word2[j - 1])                            f[i][j] = min(f[i-1][j-1], min(f[i][j-1], f[i-1][j]) + 1);                    else                        f[i][j] = min(f[i-1][j-1], min(f[i][j-1], f[i-1][j])) + 1;                }            }        }        return f[row][col];    }};




原创粉丝点击