Leetcode Edit Distance

來源:互聯網
上載者:User

標籤:style   blog   http   color   width   2014   

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

輸入兩個單詞word1和word2,求出從word1轉換成word2的最少步驟。每個轉換操作算一步。轉換操作限定於:

  • 刪除一個字元
  • 插入一個字元
  • 替換一個字元

本題用動態規劃求解

設決策變數dp[i][j],表示從word[0..i-1]轉換為word2[0...j-1]的最少步驟

可以參考http://web.stanford.edu/class/cs124/lec/med.pdf

class Solution {public:    int minDistance(string word1, string word2) {        int len1 =word1.length(), len2 = word2.length();        if(len1 == 0) return len2;        if(len2 == 0) return len1;        if(word1 == word2) return 0;        vector<vector<int> > dp(len1+1, vector<int>(len2+1,0));        for(int i = 0; i <= len1; ++ i) dp[i][0] = i;        for(int j = 0; j <= len2; ++ j) dp[0][j] = j;        for(int i =1; i <= len1; ++ i){            for(int j = 1; j <= len2; ++ j){                dp[i][j] = min(dp[i-1][j-1]+(word1[i-1] != word2[j-1]? 1: 0),min(dp[i-1][j]+1, dp[i][j-1]+1));            }        }        return dp[len1][len2];    }};

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.