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 min3(int a, int b, int c) {
return min(min(a,b), c);
}
int get_dp(int i, int j) {
if (i == 0 || j == 0) return max(i, j);
return dp[i%2][j];
}
int dp[2][100000];
int minDistance(string word1, string word2) {
memset(dp, 0, sizeof(dp));
int l1 = word1.size(), l2 = word2.size();
for (int i = 1; i <= l1; i++) {
for (int j = 1; j <= l2; j++) {
if (word1[i-1] == word2[j-1]) dp[i%2][j] = get_dp(i-1,j-1);
else {
dp[i%2][j] = min3(get_dp(i-1,j-1), get_dp(i-1,j), get_dp(i,j-1)) + 1;
}
}
}
return get_dp(l1,l2);
}
};

本文介绍了一种求解两字符串间转换所需的最小操作步骤的算法。通过插入、删除或替换字符实现转换,使用动态规划方法高效计算最短路径。
1228

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



