题目描述:
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二维数组,对每个dp[i][j]表示word1[0]-word1[i]与word2[0]-word2[j]匹配所需要的编辑距离,对于dp[i][j]有递推方法:①word1[i]=word2[j],则可以采取的编辑方法为不替换(显然替换操作是多此一举)、插入、删除,所需的编辑距离分别是dp[i-1][j-1]、dp[i-1][j]+1、dp[i][j-1]+1,所以dp[i][j]=min(dp[i-1][j-1],dp[i-1][j]+1,dp[i][j-1]+1);②word1[i]!=word2[j],则可以采取替换、插入、删除操作,所需的编辑距离分别是dp[i-1][j-1]+1、dp[i-1][j]+1、dp[i][j-1]+1,dp[i][j]=min(dp[i-1][j-1]+1,dp[i-1][j]+1,dp[i][j-1]+1)。
class Solution {
public:
int minDistance(string word1, string word2) {
word1=" "+word1;
word2=" "+word2;
int n=word1.size();
int m=word2.size();
int dp[m][n]={};
dp[0][0]=0;
for(int i=1;i<m;i++) dp[i][0]=i;
for(int j=1;j<n;j++) dp[0][j]=j;
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(word1[j]==word2[i])
{
dp[i][j]=min(dp[i-1][j-1],dp[i-1][j]+1);
dp[i][j]=min(dp[i][j],dp[i][j-1]+1);
}
else
{
dp[i][j]=min(dp[i-1][j-1]+1,dp[i-1][j]+1);
dp[i][j]=min(dp[i][j],dp[i][j-1]+1);
}
}
}
return dp[m-1][n-1];
}
};

本文介绍了一种使用动态规划解决编辑距离问题的方法。编辑距离是指通过插入、删除或替换字符将一个字符串转换为另一个字符串所需的最少步骤数。文章详细阐述了如何构建二维DP数组并给出了具体的递归公式。
1254

被折叠的 条评论
为什么被折叠?



