Lintcode-编辑距离

/*
描述
给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。

你总共三种操作方法:

插入一个字符
删除一个字符
替换一个字符

样例
给出 work1=”sailn” 和 work2=”failing”

返回 3
*/
同样利用区间型动态规划建立二维数组,并将word1作为列,Word2作为行,
初始化表如图所示。
这里写图片描述
建立状态转移方程:edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) },这里当字符串1的第i个字符不等于字符串2的第j个字符时,f(i, j) = 1;否则,f(i, j) = 0。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int min_wa(int a, int b, int c)
{
    int t = a < b ? a : b;
    return t < c ? t : c;
}

int minDistance(string &word1, string &word2) {
    // write your code here
    if(word1.empty() && word2.empty())  return 0;
    int length1 = word1.size();
    int length2 = word2.size();

    vector<vector<int>> dp(length1 + 1, vector<int>(length2 + 1));

    for(int i = 0; i <= length1; ++i)
    {
        dp[i][0] = i;
    }

    for(int i = 0; i <= length2; ++i)
    {
        dp[0][i] = i;
    }

    for(int i = 1; i <= length1; ++i)
    {
        for(int j = 1; j <= length2; ++j)
        {
            dp[i][j] = min_wa(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i - 1] == word2[j - 1] ? 0 : 1));
        }
    }

    return dp[length1][length2];
}

int main(int argc, char const *argv[])
{
    /* code */
    vector<int> A = {1, 6, 11, 5};
    string s1 = "sea";
    string s2 = "ate";

    int res = minDistance(s1, s2);

    cout << res << endl;

    return 0;
}

参考资料:http://qinxuye.me/article/get-edit-distance-by-dynamic-programming/

猜你喜欢

转载自blog.csdn.net/sinat_19596835/article/details/80625436
今日推荐