Edit Distance,editdistance
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
假如我們要將字串str1變成str2
sstr1(i)是str1的子串,範圍[0到i),sstr1(0)是空串
sstr2(j)是str2的子串,同上
d(i,j)表示將sstr1(i)變成sstr2(j)的編輯距離
首先d(0,t),0<=t<=str1.size()和d(k,0)是很顯然的。
當我們要計算d(i,j)時,即計算sstr1(i)到sstr2(j)之間的編輯距離,
此時,設sstr1(i)形式是somestr1c;sstr2(i)形如somestr2d的話,
將somestr1變成somestr2的編輯距離已知是d(i-1,j-1)
將somestr1c變成somestr2的編輯距離已知是d(i,j-1)
將somestr1變成somestr2d的編輯距離已知是d(i-1,j)
那麼利用這三個變數,就可以遞推出d(i,j)了:
如果c==d,顯然編輯距離和d(i-1,j-1)是一樣的
如果c!=d,情況稍微複雜一點,
- 如果將c替換成d,編輯距離是somestr1變成somestr2的編輯距離 + 1,也就是d(i-1,j-1) + 1
- 如果在c後面添加一個字d,編輯距離就應該是somestr1c變成somestr2的編輯距離 + 1,也就是d(i,j-1) + 1
- 如果將c刪除了,那就是要將somestr1編輯成somestr2d,距離就是d(i-1,j) + 1
那最後只需要看著三種誰最小,就採用對應的編輯方案了。
上面對演算法的分析來自於部落格uniEagle
在下面的實現代碼中,我使用滾動數組,代替了二維數組。 而且只分配了一個數組。
另外,變數dist_i1_j1 表示 d(i-1, j-1)
dist_i_j 表示 d(i,j)
dist_i1_j 表示d(i-1, j)
dist_i_j1 表示d(i, j-1)
另外,下面代碼中, 其實變數
dist_i1_j , <pre name="code" class="cpp">dist_i_j
都是可以省掉的。
不過留著,可以更直觀一點。
在leetcode上的實際執行時間為28ms。
class Solution {public: int minDistance(string word1, string word2) { if (word1.size() < word2.size()) word1.swap(word2); if (!word2.size()) return word1.size(); vector<int> dist(word2.size()); for (int j=0; j<dist.size(); j++) dist[j] = j+1; for (int i=0; i<word1.size(); i++) { int dist_i1_j1 = i; int dist_i_j1 = dist_i1_j1 +1; for (int j=0; j<word2.size(); j++) { const int dist_i1_j = dist[j]; const int dist_i_j = word1[i] == word2[j] ? dist_i1_j1 : min(min(dist_i1_j1, dist_i1_j), dist_i_j1) + 1; dist_i_j1 = dist_i_j; dist_i1_j1 = dist[j]; dist[j] = dist_i_j; } } return dist.back(); }};