Edit Distance
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
分析:只能將字符串分成更小的區間字符串來考慮,從下向上分析。那麼需要使用動態規劃的方法。
設狀態爲f[i][j],表示A[0,i]、B[0,j]之間的最小編輯距離。設A[0,i]和B[0,j]的形式爲str1c和str2d。
1、如果c==d,那麼f[i][j]=f[i-1][j-1]。
2、如果c!=d:
(1)如果將c換成d,那麼f[i][j]=f[i-1][j-1]+1;
(2)如果將c刪除,那麼f[i][j]=f[i-1][j]+1;
(3)如果將d刪除,那麼f[i][j]=f[i[j-1]+1;
/*二維動態規劃代碼*/
class Solution {
public:
int minDistance(string word1, string word2) {
int f[word1.size()+1][word2.size()+1];
int i,j;
for(i=0;i<=word1.size();i++)
f[i][0]=i;
for(j=0;j<=word2.size();j++)
f[0][j]=j;
for(int i=1;i<word1.size();i++)
for(int j=1;i<word2.size();j++)
{
if(word1[i-1]==word2[j-1])
f[i][j]=f[i-1][j-1];
else{
int mn=min(f[i][j-1],f[i-1][j]);
f[i][j]=i+min(mn,f[i-1][j-1]);
}
}
return f[word1.size()][word2.size()];
}
};
但是,在輸入規模很大時,超時。
那麼用滾動數組優化一下,節省空間。
</pre><p><pre name="code" class="cpp">class Solution {
public:
int minDistance(string word1, string word2) {
int f[word2.size()+1];
int upper_left,temp;
for(int i=0;i<=word2.size();++i)
f[i]=i;
for(int i=1;i<=word1.size();i++){
upper_left=f[0];
f[0]=i;
for(int j=1;j<=word2.size();j++)
{
if(word1[i-1]==word2[j-1]){
temp=f[j];
f[j]=upper_left;
upper_left=temp;
}
else{ // upper_left相當於 f[i-1][j-1],f[j-1]相當於f[i][j-1]
int mn=min(upper_left,f[j-1]);
temp=f[j];
f[j]=1+min(f[j],mn); //f[j]相當於f[i-1][j]
upper_left=temp;
}
}
}
return f[word2.size()];
}
};
學習:https://gitcafe.com/soulmachine/LeetCode