[LeetCode] 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
这里我想解释一下
D[i,j] = D[i-1,j]+del[x(i)];
D[i,j]表示X[1,i]到Y[1,j]的ED,D[i-1,j]表示X[1,i-1]到Y[1,j]的ED,而由X[1,i]到X[1,i-1]的步骤就是del[x(i)]
同理,D[1,j-1]表示X[1,i]到Y[1,j-1]的ED,而由Y[1,i-1]到Y[1,i]的步骤就是ins[y(i)]
小结一下
思路:
X[1,i]-->Y[1,j]有三中方法:
1. 首先X[1,i]-->X[1,i-1] (就是del x(i)) ,然后X[1,i-1]-->Y[1,j]
2 首先X[1,i]-->Y[1,j-1],然后Y[1,j-1]-->Y[1,j](就是ins y(j))
3 就是X[1,i-1]-->Y[1,j-1],然后替换
为什么不能X[i+1] --> X[i]; 是删除操作,其实说明X[i] -->X[i+1]是插入操作,他们是相互可以转变的
考虑特殊情况Y为空串,那么X[1,i] -->Y 就需要 i 步骤,而X[1,i+1] -->Y 就需要 i +1步骤
因此,我们考虑问题时X[1,i]-->Y[1,j]只关注 <=i, <=j 的情况,不关注大于i,j的情况
考虑整个字符串 str1 和 str2 ,str1 写作&&&&&&&&&&&&&X,str2 写作%%%%%%%%%%%%%Y
&&&&&&&&&&&&&X
%%%%%%%%%Y
就要考虑【&&&&&&&&&&&&&,%%%%%%%%%Y】【&&&&&&&&&&&&&X,%%%%%%%%%】【&&&&&&&&&&&&&,%%%%%%%%%】3中情况即可,所以子问题也考虑着三种情况
1 class Solution { 2 public: 3 int minDistance(string word1, string word2) 4 { 5 size_t size1 = word1.size(); 6 size_t size2 = word2.size(); 7 8 vector <vector<int> >f; 9 vector<int> a; 10 a.resize(size2+1, 0); 11 for(int i = 0; i< size1+1; i++) 12 { 13 f.push_back(a); 14 } 15 16 for(int i = 0; i<= size1; i++) 17 f[i][0] = i; 18 for(int i = 0; i<= size2; i++) 19 f[0][i] = i; 20 21 for(int i = 0; i< size1; i++) 22 { 23 for(int j = 0; j< size2; j++) 24 { 25 26 int min1 = f[i][j+1]; 27 min1 = min(min1, f[i+1][j]) + 1; 28 int min2 = f[i][j]; 29 if(word1[i] != word2[j]) 30 min2++; 31 f[i+1][j+1]= min(min1, min2); 32 } 33 } 34 35 return f[size1][ size2]; 36 } 37 };