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 m = word1.size();
int n = word2.size();
int sum[m+1][n+1];
for(int i=0;i<m+1;i++)
sum[i][0] = i;
for(int j=0;j<n+1;j++)
sum[0][j] = j;
for(int i=1;i<m+1;i++)
for(int j=1;j<n+1;j++)
{
if (word1[i-1] == word2[j-1])
sum[i][j] = sum[i-1][j-1];
else
sum[i][j] = sum[i-1][j-1] + 1;
sum[i][j] = min(sum[i][j], min(sum[i-1][j]+1, sum[i][j-1]+1));
}
return sum[m][n];
}
};
书上的题目,还是想了一下
本文介绍了一种求解两字符串间转换所需的最小操作步骤的算法。通过插入、删除或替换字符实现转换,适用于编辑距离问题。算法使用动态规划方法,提供了一个C++实现示例。
1252

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



