算法练习9:leetcode习题72. Edit Distance

题目

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:
Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)

Example 2:
Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)

算法思路

本周继续学习动态规划的问题,本题是动态规划里面的经典问题——编辑距离。
两个字符串的编辑距离指的是将两个字符串上下排列时,其字母不同的列数的最小值。它的一种实际意义就是题目上面的表述,将一个字符串变为另一个字符串所要进行的最小操作数,合法操作有插入、删除、替换。
我们拆解最后一位字符可能的情况
分解子问题的状态方程
dis[i][j] =min{1+dis[i-1][j], 1+dis[i][j-1], diff(i,j)+dis[i-1][j-1]}
dis[i][j]表示word1的前i个字符与word2的前j个字符的编辑距离
如果word1[i]==word2[j], diff(i,j)=0,否则diff(i,j)=1.

C++代码

class Solution {
public:
    int minDistance(string word1, string word2) {
		int dis[word1.size()+1][word2.size()+1];

        for (int i = 0; i <= word2.size(); ++i)
        {
            dis[0][i] = i;
        }

        for (int i = 1; i <= word1.size(); ++i)
        {
            dis[i][0] = i;
        }

        for (int i = 1; i <= word1.size(); ++i)
        {
            for (int j = 1; j <= word2.size(); ++j)
            {
                int temp = dis[i-1][j] < dis[i][j-1]?dis[i-1][j]:dis[i][j-1];
                temp++;
                int diff = 1;
                if (word1[i-1] == word2[j-1])
                {
                    diff = 0;
                }
                if (diff + dis[i-1][j-1] < temp)
                {
                    temp = diff + dis[i-1][j-1];
                }
                dis[i][j] = temp;
            }
        }

        return dis[word1.size()][word2.size()];

    }
};

猜你喜欢

转载自blog.csdn.net/m0_37779608/article/details/83663598