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(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,情况稍微复杂一点,
那最后只需要看着三种谁最小,就采用对应的编辑方案了。
在下面的实现代码中,我使用滚动数组,代替了二维数组。 而且只分配了一个数组。
另外,变量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(); } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/44981805