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
题意:
编辑距离
思路:
找到状态转移方程就好了。
代码:
class Solution {
public:
int minDistance(string word1, string word2) {
int l1=word1.length();
int l2=word2.length();
int a[l1+1][l2+1];
a[0][0]=0;
for(int i=1;i<=l1;i++)
a[i][0]=i;
for(int j=1;j<=l2;j++)
a[0][j]=j;
for(int i=1;i<=l1;i++)
{
for(int j=1;j<=l2;j++)
{
if(word1[i-1]==word2[j-1])
a[i][j]=min(a[i][j-1]+1,min(a[i-1][j]+1,a[i-1][j-1]));
else
a[i][j]=min(a[i][j-1],min(a[i-1][j],a[i-1][j-1]))+1;
}
}
return a[l1][l2];
}
};
参考博客