leetcode题解c++ | 72. Edit Distance

来源:互联网 发布:淘宝小号账号查询 编辑:程序博客网 时间:2024/06/12 23:01

题目:https://leetcode.com/problems/edit-distance/#/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

分析

这是一道动态规划问题,关键是写出转移方程。dp[i][j] 表示从word1的i位置之前的串到word2的j位置之前的串,所需变动的步数。dif[i][j]为word1[i]和word1[j]是否相同。转移方程为

dp[i][j] = min(dp[i-1][j] +1, dp[i][j-1] + 1, dp[i-1][j-1]+dif[i][j])

c++实现

int minDistance(string word1, string word2){    //dp[i][j] 表示从word1的i位置之前的串到word2的j位置之前的串,所需变动的步数    int len1 = word1.length();    int len2 = word2.length();    int dp[len1+1][len2+1], dif[len1+1][len2+1];    for(int i=0; i<len1; ++i)        for(int j=0; j<len2; ++j)            if(word1[i]==word2[j])                dif[i+1][j+1] = 0;            else                dif[i+1][j+1] = 1;    for(int i=0; i<=len1; ++i)        dp[i][0] = i;    for(int i=0; i<=len2; ++i)        dp[0][i] = i;    for(int i=1; i<=len1; ++i)        for(int j=1; j<=len2; ++j)            dp[i][j] = min(min(dp[i-1][j],dp[i][j-1])+1, dp[i-1][j-1]+dif[i][j]);    return dp[len1][len2];}


0 0
原创粉丝点击