leetcode Edit Distance

来源:互联网 发布:查看矢量图的软件 编辑:程序博客网 时间:2024/06/14 17:49

Description:

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


Solution:

状态转移方程如下

1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i-1, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1  if A[i] != B[j]


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


原创粉丝点击