Edit Distance,editdistance

來源:互聯網
上載者:User

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,情況稍微複雜一點,

    1. 如果將c替換成d,編輯距離是somestr1變成somestr2的編輯距離 + 1,也就是d(i-1,j-1) + 1
    2. 如果在c後面添加一個字d,編輯距離就應該是somestr1c變成somestr2的編輯距離 + 1,也就是d(i,j-1) + 1
    3. 如果將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();    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.