LeetCode 72 Edit Distance DP
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Solution
设 \(dp[i][j]\) 表示将 word1
的 \([0,...,i)\) 转变为 word2
的 \([0,...,j)\) 的最小操作数。对于初始化,即考虑某一个串为空串,操作数自然为另一个非空串的长度:
\[dp[i][0] = i;dp[0][j] = j
\]
现考虑转移:假设现在已经知道了 \(dp[i][j]\) 之前的所有状态最小操作数,如果 \(s1[i]==s2[j]\),则直接:
\[dp[i][j] = dp[i-1][j-1]
\]
否则,则是考虑三个操作所带来的花费:
- 最简单的就是 replace: \(dp[i][j] = dp[i-1][j-1]+1\)
- 如果 \(s1[0,...,i-1) =s2[0,...,j)\),则直接 delete \(s[i-1]\):
\[dp[i][j] = dp[i-1][j]+1
\]
- 如果 \(s1[0,...,i)+s2[j-1]=s2[0,...,j)\),则进行 insert:
\[dp[i][j] = dp[i][j-1]+1
\]
点击查看代码
class Solution {
private:
int dp[505][505];
public:
int minDistance(string word1, string word2) {
int n = word1.length(), m = word2.length();
// dp[i][j]: word1[0,...,i) word2[0,...,j)
for(int i=0;i<=n;i++)dp[i][0] = i;
for(int i=0;i<=m;i++)dp[0][i] = i;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(word1[i-1]==word2[j-1])dp[i][j] = dp[i-1][j-1];
else{
// word1[i-1]!=word2[j-1]
// dp[i-1][j-1] is known now
// Replace: dp[i][j] = dp[i-1][j-1]+1;
// Delete: dp[i][j] = dp[i-1][j]+1;
// Insert: dp[i][j] = dp[i][j-1]+1;
dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
}
}
}
return dp[n][m];
}
};