Edit Distance(动态规划)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36124194/article/details/83716115

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:

Insert a character
Delete a character
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’)

分析

用动态规划的思想去解决这个问题,那么意味着我们需要寻找这两个字符串的子问题的解,那么这个子问题怎么解决呢?
我们采用一个二维数组来表示count[i][j]表示字符串长为i和字符串长为j的字符的编辑距离,对于子问题,我们可以采用将i和j逐步缩小的策略,那么最终问题可以看作解决count[i][j],而每个字符串与空串的编辑距离是明显的,及count[0][j]和count[i][0]是明显知道的。
那么对于子问题可以有一下三种情况
在这里插入图片描述
最后可以知道状态转移方程为:
在这里插入图片描述
其中diff(i,j)是指当串1和串2的下标i和下标j对应的字符相等的时候为0,否则需要一步编辑距离,则为1.

源码

class Solution {
public:
    int minDistance(string word1, string word2) {
        int size1 = word1.size();
        int size2 = word2.size();
        vector<vector<int>> count(size1+1, vector<int>(size2+1, 0));
        for(int i = 0; i <= size1; i++) {
        	count[i][0] = i;
        }
        for(int i = 0; i <= size2; i++) {
        	count[0][i] = i;
        }

        for(int i = 1; i <= size1; i++) {
        	for(int j = 1; j <= size2; j++) {
        		int tag = 0;
        		if(word1[i-1] != word2[j-1]) {
        			tag = 1;
        		}
        		count[i][j] = min(count[i-1][j]+1, count[i][j-1]+1);
        		count[i][j] = min(count[i][j], tag+count[i-1][j-1]);
        	}
        }
        return count[size1][size2];
    }
};

觉得博主写的好
在这里插入图片描述

更多技术博客https://vilin.club/

展开阅读全文

没有更多推荐了,返回首页